Skip to content

Commit fd548a8

Browse files
both iterative and recursive solutions for Reverse Linked List.
1 parent ab11f6b commit fd548a8

File tree

1 file changed

+36
-4
lines changed

1 file changed

+36
-4
lines changed

EASY/src/easy/ReverseLinkedList.java

+36-4
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,12 @@
44
import classes.ListNode;
55

66
public class ReverseLinkedList {
7-
//there's no reversion if the list is null or it contains only one node, so at a minimum, there should be 2 nodes
8-
public ListNode reverseList(ListNode head) {
7+
//creating a newHead = null is a very common/smart way to handle such cases, the logic flows out very naturally:
8+
//create a new node called "next" to hold current head's next node
9+
//then we could redirect head's next pointer to point to newHead which is head's previous node
10+
//the above two steps finished the reversion, to continue this process until we reach the end of the original list,
11+
//we'll assign current "head" to new "newHead", and current "next" to be new "head" for the next iteration, here's the code
12+
public ListNode reverseList_iterative(ListNode head) {
913
ListNode newHead = null;
1014
while(head != null){
1115
ListNode next = head.next;
@@ -15,16 +19,44 @@ public ListNode reverseList(ListNode head) {
1519
}
1620
return newHead;
1721
}
22+
23+
//following the above iterative version, the recursive solution flows out so naturally, basically, we just replaced the while loop with a recursive function
24+
//still, a null newHead proves to be very helpful.
25+
public ListNode reverseList_recursive(ListNode head) {
26+
ListNode newHead = null;
27+
return reverse(head, newHead);
28+
}
29+
30+
private ListNode reverse(ListNode head, ListNode newHead) {
31+
if(head != null){
32+
ListNode next = head.next;
33+
head.next = newHead;
34+
newHead = head;
35+
head = next;
36+
return reverse(head, newHead);
37+
}
38+
else return newHead;
39+
}
40+
41+
//the above recursive function could of course be shortened to below, but the above one is just more intuitive and easier to follow and sort out your logic
42+
private ListNode reverse_more_concise(ListNode head, ListNode newHead) {
43+
if(head != null){
44+
ListNode next = head.next;
45+
head.next = newHead;
46+
return reverse_more_concise(next, head);
47+
} else return newHead;
48+
}
1849

19-
public static void main(String...strings){
50+
public static void main(String...strings){
2051
ReverseLinkedList test = new ReverseLinkedList();
2152
ListNode head = new ListNode(1);
2253
head.next = new ListNode(2);
2354
head.next.next = new ListNode(3);
2455
head.next.next.next = new ListNode(4);
2556
head.next.next.next.next = new ListNode(5);
2657
CommonUtils.printList(head);
27-
ListNode result = test.reverseList(head);
58+
// ListNode result = test.reverseList_iterative(head);
59+
ListNode result = test.reverseList_recursive(head);
2860
CommonUtils.printList(result);
2961
}
3062

0 commit comments

Comments
 (0)