Author: techfox9

Reversing a singly-linked list in Java .. iterative and recursive methods ..

Sunday, December 27th, 2009 @ 11:31 am

From http://www.java2blog.com/2014/07/how-to-reverse-linked-list-in-java.html

[java]

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;
}

[/java]

Recursive method:

[java]
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;
}
[/java]

. . .

Algorithms, Java


 


Comments are closed.