struct node {
int data ;
struct node* next ;
}
// use pointer to node because we gotta change head reference value in function
void reverseList(node** head)
{
struct node* current = *head;
struct node* prev = NULL;
struct node* next ;
while( current != NULL)
{
//save next node
next = current->next;
//shift previous node , reversing two nodes at a time (current and previous)
current->next = prev ;
//update prev
prev = current ;
//update current pointing rest of the list
current = next ;
}
//update head
*head = prev ;
}
Simple Visualisation inside loop
Sample linked list
1 -> 2 -> 3
Iterations :
1 : 1-> NULL (*prev == 1 ) , 2->3 (*current == 2)
2 : 2->1->NULL (*prev == 2) , 3-> NULL
3: 3->2->1-> (*prev == 3) , NULL
Loop over , update *head = prev
int data ;
struct node* next ;
}
// use pointer to node because we gotta change head reference value in function
void reverseList(node** head)
{
struct node* current = *head;
struct node* prev = NULL;
struct node* next ;
while( current != NULL)
{
//save next node
next = current->next;
//shift previous node , reversing two nodes at a time (current and previous)
current->next = prev ;
//update prev
prev = current ;
//update current pointing rest of the list
current = next ;
}
//update head
*head = prev ;
}
Simple Visualisation inside loop
Sample linked list
1 -> 2 -> 3
Iterations :
1 : 1-> NULL (*prev == 1 ) , 2->3 (*current == 2)
2 : 2->1->NULL (*prev == 2) , 3-> NULL
3: 3->2->1-> (*prev == 3) , NULL
Loop over , update *head = prev
No comments:
Post a Comment