So i am trying to solve a problem to reverse a linked list and following is what i came up with.
class Solution
{
public:
/* void insertList(struct Node* head, int data)
{
Node* temp{ head };
while (temp->next != nullptr)
{
temp = temp->next;
}
Node* nextNode{ new Node(data) };
temp->next = nextNode;
}*/
void insertPrev(struct Node* revHead, int data)
{
Node* temp{ new Node(data) };
temp->next = revHead;
revHead = temp;
}
//Function to reverse a linked list.
struct Node* reverseList(struct Node* head)
{
if (head == NULL)
return head;
Node* revHead{ new Node(head->data) };
Node* temp{ head->next };
while (temp != NULL);//this line
{
insertPrev(revHead, temp->data);//this line 2
temp = temp->next;
}
return revHead;
}
};
when i am trying to run this code to reverse a linked list. it gets stuck infinitely on this line which i have commented as this line. Moreover, ide throws warning also that i may be potentially derefercing a null pointer in this line 2. I don't know how is that possible when i just checked above that temp should not be null for the while loop to run. Help please!