Iterative:
Logic for this would be:
Have three nodes i.e previousNode,currentNode and nextNode
When currentNode is starting node, then previousNode will be null
Assign currentNode.next to previousNode to reverse the link.
In each iteration move currentNode and previousNode by 1 node.
Logic for this would be:
Have three nodes i.e previousNode,currentNode and nextNode
When currentNode is starting node, then previousNode will be null
Assign currentNode.next to previousNode to reverse the link.
In each iteration move currentNode and previousNode by 1 node.
public static Node reverseLinkedList(Node currentNode) { // For first node, previousNode will be null Node previousNode=null; Node nextNode; while(currentNode!=null) { nextNode=currentNode.next; // reversing the link currentNode.next=previousNode; // moving currentNode and previousNode by 1 node previousNode=currentNode; currentNode=nextNode; } return previousNode; }
No comments:
Post a Comment