How to reverse a linked list using recursion and iteration?
In the iteration approach we reverse linked list using 3 pointers in O(n) time, This is done by creating a new list by reversing direction, and subsequently inserting the element at the start of the list.
We can also reverse a singly linked list by using recursion. We will traverse the linked list until we find the tail, this tail would be the new head for reversed linked list.
-K Himaanshu Shuklaa..
In the iteration approach we reverse linked list using 3 pointers in O(n) time, This is done by creating a new list by reversing direction, and subsequently inserting the element at the start of the list.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public void reverseIteratively(Node head) { | |
Node current = head; | |
Node previous = null; | |
Node forward = null; | |
while(current.next != null){ | |
// Saving reference of next node, since we are changing current node | |
forward = current.next; | |
// Inserting node at start of new list | |
current.next = previous; | |
previous = current; | |
// Advancing to next node | |
current = forward; | |
} | |
head = current; | |
head.next = previous; | |
} | |
We can also reverse a singly linked list by using recursion. We will traverse the linked list until we find the tail, this tail would be the new head for reversed linked list.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
private Node reverseRecursively(Node node){ | |
Node newHead; | |
//corner case | |
if((node.next == null)) | |
return node; | |
newHead = reverseRecursively(node.next); | |
//reverse the link | |
node.next.next = node; | |
node.next = null; | |
return newHead; | |
} |
-K Himaanshu Shuklaa..
No comments:
Post a Comment