In this article, we will see Java program to reverse Linked List using iterative and recursive approach.
Iterative approach
Steps :
Declare previous, current and next nodes.
Until current node is null, do this :
next = current.next
current.next = previous
previous = current
current = next
return the previous node
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | private Node reverseIterative(Node head) { Node prev = null, curr = head; while (curr != null) { Node next = curr.next; curr.next = prev; prev = curr; curr = next; } return prev; } |
Reverse Linked List using recursion
1 2 3 4 5 6 7 8 9 10 11 12 | //reverse using Recursion private Node reverseRecursive(Node head) { if(head==null || head.next == null) return head; Node n = reverseRecursive(head.next); head.next.next = head;//n+1 th node pointing nth node head.next = null; return n; } |
© 2018, www.topjavatutorial.com. All rights reserved. On republishing this post, you must provide link to original post