@@ -14,42 +14,42 @@ public String toString() {
14
14
}
15
15
}
16
16
17
- public static void main (String [] args ) {
18
- ListNode head = new ListNode (1 );
19
- head .next = new ListNode (2 );
20
- head .next .next = new ListNode (3 );
21
- head .next .next .next = new ListNode (4 );
22
- head .next .next .next .next = new ListNode (5 );
23
- System .out .println (reverseBetween (head , 2 , 4 ));
24
- }
17
+ public ListNode reverseBetween (ListNode head , int m , int n ) {
18
+ if (head == null || m == n ) {
19
+ return head ;
20
+ }
25
21
26
- public static ListNode reverseBetween (ListNode head , int leftVal , int rightVal ) {
27
- if (leftVal == rightVal ) return head ;
22
+ // Move the two pointers until they reach the proper starting point
23
+ // in the list.
24
+ ListNode cur = head , prev = null ;
25
+ while (m > 1 ) {
26
+ prev = cur ;
27
+ cur = cur .next ;
28
+ m --;
29
+ n --;
30
+ }
28
31
29
- ListNode sentinelHead = new ListNode (-1000 );
30
- sentinelHead .next = head ;
31
- ListNode beforeLeft = getNodeBefore (sentinelHead , leftVal );
32
- System .out .println (beforeLeft .val );
33
- ListNode left = beforeLeft .next ;
34
- ListNode a = beforeLeft .next , b = a .next , c = b .next ;
32
+ // The two pointers that will fix the final connections.
33
+ ListNode con = prev , tail = cur ;
35
34
36
- while (c != null && b .val != rightVal ) {
37
- a .next = null ;
38
- b .next = a ;
39
- a = b ;
40
- b = c ;
41
- c = c .next ;
35
+ // Iteratively reverse the nodes until n becomes 0.
36
+ ListNode third = null ;
37
+ while (n > 0 ) {
38
+ third = cur .next ;
39
+ cur .next = prev ;
40
+ prev = cur ;
41
+ cur = third ;
42
+ n --;
42
43
}
43
- b .next = a ;
44
- beforeLeft .next = b ;
45
- left .next = c ;
46
- return sentinelHead .next ;
47
- }
48
44
49
- private static ListNode getNodeBefore (ListNode head , int value ) {
50
- while (head != null && head .next != null && head .next .val != value ) {
51
- head = head .next ;
45
+ // Adjust the final connections
46
+ if (con != null ) {
47
+ con .next = prev ;
48
+ } else {
49
+ head = prev ;
52
50
}
51
+
52
+ tail .next = cur ;
53
53
return head ;
54
54
}
55
55
}
0 commit comments