|
15 | 15 | */
|
16 | 16 | public class _143 {
|
17 | 17 |
|
18 |
| - public void reorderList(ListNode head) { |
19 |
| - if (head == null || head.next == null) { |
20 |
| - return; |
21 |
| - } |
22 |
| - /* first we use two pointers to separate this list into two parts */ |
23 |
| - ListNode slowNode = head; |
24 |
| - ListNode fastNode = head; |
25 |
| - while (fastNode.next != null) { |
26 |
| - fastNode = fastNode.next; |
27 |
| - if (fastNode.next != null) { |
| 18 | + public static class Solution1 { |
| 19 | + public void reorderList(ListNode head) { |
| 20 | + if (head == null || head.next == null) { |
| 21 | + return; |
| 22 | + } |
| 23 | + /* first we use two pointers to separate this list into two parts */ |
| 24 | + ListNode slowNode = head; |
| 25 | + ListNode fastNode = head; |
| 26 | + while (fastNode.next != null) { |
28 | 27 | fastNode = fastNode.next;
|
29 |
| - } else { |
30 |
| - break; |
| 28 | + if (fastNode.next != null) { |
| 29 | + fastNode = fastNode.next; |
| 30 | + } else { |
| 31 | + break; |
| 32 | + } |
| 33 | + slowNode = slowNode.next; |
31 | 34 | }
|
32 |
| - slowNode = slowNode.next; |
33 |
| - } |
34 |
| - // two sublist heads |
35 |
| - ListNode head1 = head; |
36 |
| - ListNode head2 = slowNode.next; |
37 |
| - // detach the two sublists; |
38 |
| - slowNode.next = null; |
| 35 | + // two sublist heads |
| 36 | + ListNode head1 = head; |
| 37 | + ListNode head2 = slowNode.next; |
| 38 | + // detach the two sublists; |
| 39 | + slowNode.next = null; |
39 | 40 |
|
40 |
| - // reverse the second sublist |
41 |
| - ListNode cur = head2; |
42 |
| - ListNode post = cur.next; |
43 |
| - cur.next = null; |
44 |
| - while (post != null) { |
45 |
| - ListNode temp = post.next; |
46 |
| - post.next = cur; |
47 |
| - cur = post; |
48 |
| - post = temp; |
49 |
| - } |
50 |
| - head2 = cur;// the new head of the reversed sublist |
| 41 | + // reverse the second sublist |
| 42 | + ListNode cur = head2; |
| 43 | + ListNode post = cur.next; |
| 44 | + cur.next = null; |
| 45 | + while (post != null) { |
| 46 | + ListNode temp = post.next; |
| 47 | + post.next = cur; |
| 48 | + cur = post; |
| 49 | + post = temp; |
| 50 | + } |
| 51 | + head2 = cur;// the new head of the reversed sublist |
51 | 52 |
|
52 |
| - // merge the two sublists as required |
53 |
| - ListNode p = head1; |
54 |
| - ListNode q = head2; |
55 |
| - while (q != null) { |
56 |
| - ListNode temp1 = p.next; |
57 |
| - ListNode temp2 = q.next; |
58 |
| - p.next = q; |
59 |
| - q.next = temp1; |
60 |
| - p = temp1; |
61 |
| - q = temp2; |
| 53 | + // merge the two sublists as required |
| 54 | + ListNode p = head1; |
| 55 | + ListNode q = head2; |
| 56 | + while (q != null) { |
| 57 | + ListNode temp1 = p.next; |
| 58 | + ListNode temp2 = q.next; |
| 59 | + p.next = q; |
| 60 | + q.next = temp1; |
| 61 | + p = temp1; |
| 62 | + q = temp2; |
| 63 | + } |
62 | 64 | }
|
63 | 65 | }
|
64 |
| - |
65 | 66 | }
|
0 commit comments