There are two way to reverse a linked list that are using recursion or using iteration.
This operation takes O(n) time complexity during iteration method.
Here is the code to reverse linked list using iterator :
public void reverseLinkedList(Node curNode){
Node prevBode = null;
Node nextNode = null;
while(curNode != null){
nextNode = curNode.next;
curNode.next = prevNode;
curNode = nextNode;
prevNode = curNode;
}
return prevNode;
}
Here is method to reverse linked list recursively :
public Node reverseLinkList(Node node) {
if (node == null || node.next == null) {
return node;
}
Node rest = reverseLinkList(node.next);
node.next.next = node;
node.next = null;
return rest;
}
0 Comment(s)