7
7
* }
8
8
*/
9
9
class Solution {
10
- // recursion
11
10
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 );
14
13
}
15
14
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 ;
23
26
}
24
27
28
+ public ListNode recursive (ListNode head ) {
29
+ return recurHelper (head , null );
30
+ }
25
31
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 );
39
37
}
40
38
}
0 commit comments