#include "bits/stdc .h"
using namespace std;
struct ListNode
{
int val ;
ListNode * next;
ListNode( int c )
{
val = c;
next = NULL;
}
};
void traversal ( ListNode * head )
{
ListNode*temp = head ;
while ( temp != NULL)
{
cout << temp->val << " ";
temp=temp->next;
}
cout<<endl;
}
ListNode* reverseList(ListNode* head)
{
ListNode * temp=head;
ListNode *p=head;
ListNode *x=NULL ;
while( head->val != x-> val )
{
while( temp->next != x)
temp=temp->next;
swap(head->val,temp->next->val);
x=temp->next;
head=head->next;
temp= head ;
}
return p;
}
int main()
{
ListNode * head = new ListNode ( 10 );
head->next = new ListNode ( 20 );
head-> next -> next =new ListNode ( 30 );
head-> next -> next-> next =new ListNode ( 40 );
head-> next -> next-> next-> next =new ListNode ( 50 );
traversal ( head ) ;
head = reverseList ( head ) ;
traversal ( head ) ;
return 0 ;
}
OUTPUT:
10 20 30 40 50
The program ends after printing this.
I'm trying to reverse a singly linked list. I know this is not the right algorithm, I'm just creating my own algo to reverse it.I'm trying to maintain 2 pointer to swap the last and the first element till we reach the middle where the head -> data == x-> data . I'm using x pointer to store the address of the nth node ( in this case say address of 50 ) so that the next time my list iterates till over the second last element.The problem is that my list is not getting printed when i call the function.
CodePudding user response:
Basically this is what you need to do:
ListNode* reverseList(ListNode* head)
{
ListNode *current = head;
ListNode *previous = NULL;
while (current != NULL) {
ListNode *next = current->next;
current->next = previous;
previous = current;
current = next;
}
head = previous;
return head;
}
Your while
was looping with the condition of ( head->val != x-> val )
, and temp
is initialized with head
, so the two values will always match and as a result, the while
condition will never be true.
CodePudding user response:
ListNode* reverseList(ListNode* head)
{
ListNode * temp=head, *p=head, *x=head;
while ( x->next !=NULL)
x=x->next;
while( head->val != x-> val )
{
while( temp->next != x)
{
temp=temp->next;
}
swap(head->val,temp->next->val);
x=temp;
head=head->next;
temp= head ;
}
return p;
}
Fixed it :)