0% found this document useful (0 votes)
1 views6 pages

Reversing Single Linked List

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views6 pages

Reversing Single Linked List

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 6

Reversing Single

Linked List
Single Linked List: Reversing
Reversing a list can be performed in two ways:
• Iterative method
• Recursive method

Steps to reverse a Singly Linked List using Iterative method


Step 1: Create two more pointers other than head namely prevNode and curNode that will
hold the reference of previous node and current node respectively.
• Make sure that prevNode points to first node i.e. prevNode = head.
• head should now point to its next node i.e. head = head->next.
• curNode should also points to the second node i.e. curNode = head.
Reversing a List
Step 2: Now, disconnect the first node from others. We will make sure that it points to none.
As this node is going to be our last node. Perform operation prevNode->next = NULL.

Step 3: Move the head node to its next node i.e. head = head->next.
Reversing a List
Step 4: Now, re-connect the current node to its previous node
i.e. curNode->next = prevNode;

Step 5: Point the previous node to current node and current node to head node. Means they
should now point to prevNode = curNode; and curNode = head.
Reversing a List
Step 6: Repeat steps 3-5 till head pointer becomes NULL.

Step 7: Now, after all nodes has been re-connected in the reverse order. Make the last node
as the first node. Means the head pointer should point to prevNode pointer.
• Perform head = prevNode; And finally you end up with a reversed linked list of
its original.
Reversing a List: Iterative Method
Struct node* reverseList(struct node*h)
{
struct node *prevNode, *curNode;
if(h != NULL)
{
prevNode = h;
curNode = h->next;
h = h->next;

prevNode->next = NULL; //Makes the first node as last node

while(h != NULL)
{
h = h->next;
curNode->next = prevNode;

prevNode = curNode;
curNode = h;
}

h = prevNode; //Makes the last node as head


return(h);
}
}

You might also like