Reversing a singly-linked list in Java .. iterative and recursive methods ..
Dec 27, 2009 in Algorithms, Java
From http://www.java2blog.com/2014/07/how-to-reverse-linked-list-in-java.html
public void reverse(ListNode head) { ListNode curr = head; ListNode prev = null; ListNode next = null; while (curr != null) { next = curr.next; curr.next = prev; // reverse link to previous prev = curr; curr = next; } return prev; }
Recursive method:
public ListNode reverseList(ListNode head) { // from: http://www.java2blog.com/2014/07/how-to-reverse-linked-list-in-java.html if ( head == null || head.next == null ) return head; ListNode rlist = reverseList(head.next); head.next.next = head; head.next = null; return rlist; }
. . .