|
| 1 | +// T: O(n) |
| 2 | +// S: O(1) |
| 3 | + |
1 | 4 | public class ReverseLinkedListII {
|
2 | | - private static class ListNode { |
| 5 | + public static class ListNode { |
3 | 6 | int val;
|
4 | 7 | ListNode next;
|
| 8 | + ListNode() {} |
5 | 9 | ListNode(int val) { this.val = val; }
|
6 | | - |
7 | | - @Override |
8 | | - public String toString() { |
9 | | - if (next == null) return "ListNode{val=" + val + ", next=null}"; |
10 | | - return "ListNode{" + |
11 | | - "val=" + val + |
12 | | - ", next=" + next + |
13 | | - '}'; |
14 | | - } |
| 10 | + ListNode(int val, ListNode next) { this.val = val; this.next = next; } |
15 | 11 | }
|
16 | 12 |
|
17 | | - public ListNode reverseBetween(ListNode head, int m, int n) { |
18 | | - if (head == null || m == n) { |
19 | | - return head; |
20 | | - } |
| 13 | + public ListNode reverseBetween(ListNode head, int left, int right) { |
| 14 | + if (left == right) return head; |
21 | 15 |
|
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--; |
| 16 | + ListNode start = new ListNode(); |
| 17 | + start.next = head; |
| 18 | + |
| 19 | + ListNode temp = start; |
| 20 | + int i = 1; |
| 21 | + for ( ; i < left ; i++) { |
| 22 | + temp = temp.next; |
30 | 23 | }
|
31 | 24 |
|
32 | | - // The two pointers that will fix the final connections. |
33 | | - ListNodecon = prev, tail = cur; |
| 25 | + ListNodea = temp.next, b = temp.next.next, c = temp.next.next.next; |
| 26 | + a.next = null; |
34 | 27 |
|
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--; |
| 28 | + for ( ; i < right && c != null; i++) { |
| 29 | + b.next = a; |
| 30 | + a = b; |
| 31 | + b = c; |
| 32 | + c = c.next; |
43 | 33 | }
|
44 | | - |
45 | | - // Adjust the final connections |
46 | | - if (con != null) { |
47 | | - con.next = prev; |
48 | | - } else { |
49 | | - head = prev; |
| 34 | + if (i < right) { |
| 35 | + b.next = a; |
| 36 | + if (left != 1) { |
| 37 | + temp.next = b; |
| 38 | + return start.next; |
| 39 | + } |
| 40 | + return b; |
50 | 41 | }
|
51 | | - |
52 | | - tail.next = cur; |
53 | | - return head; |
| 42 | +temp.next.next = b; |
| 43 | + temp.next = a; |
| 44 | + return start.next; |
54 | 45 | }
|
55 | 46 | }
|
0 commit comments