Skip to content

Commit 0ec4081

Browse files
authored
Iter: dr, cur, next; Recur: helper(ori, tail)
1 parent 49f4f7a commit 0ec4081

File tree

1 file changed

+21
-23
lines changed

1 file changed

+21
-23
lines changed

Reverse Linked List.java

+21-23
Original file line numberDiff line numberDiff line change
@@ -7,34 +7,32 @@
77
* }
88
*/
99
class Solution {
10-
// recursion
1110
public ListNode reverseList(ListNode head) {
12-
// use helper with two input nodes, one for attach at end, one for unprocessed part
13-
return helper(head, null);
11+
// return iterative(head);
12+
return recursive(head);
1413
}
1514

16-
public ListNode helper(ListNode unPro, ListNode tail) {
17-
// unPro: head of unprocessed; tail: what to attach at the tail
18-
if(unPro == null) return tail;
19-
ListNode nextUnPro = unPro.next;
20-
unPro.next = tail;
21-
ListNode newHead = helper(nextUnPro, unPro);
22-
return newHead;
15+
public ListNode iterative(ListNode head) {
16+
ListNode dr = new ListNode(0);
17+
ListNode cur = head;
18+
19+
while(cur != null) {
20+
ListNode next = cur.next;
21+
cur.next = dr.next;
22+
dr.next = cur;
23+
cur = next;
24+
}
25+
return dr.next;
2326
}
2427

28+
public ListNode recursive(ListNode head) {
29+
return recurHelper(head, null);
30+
}
2531

26-
// iterative
27-
public ListNode reverseList(ListNode head) {
28-
if(head == null) return head;
29-
// cur cannot be root
30-
ListNode root = new ListNode(0), cur = head, next = head.next;
31-
root.next = head;
32-
while(next != null) {
33-
cur.next = next.next;
34-
next.next = root.next;
35-
root.next = next;
36-
next = cur.next;
37-
}
38-
return root.next;
32+
public ListNode recurHelper(ListNode ori, ListNode tail) {
33+
if(ori == null) return tail;
34+
ListNode nextOri = ori.next;
35+
ori.next = tail;
36+
return recurHelper(nextOri, ori);
3937
}
4038
}

0 commit comments

Comments
 (0)