-
Notifications
You must be signed in to change notification settings - Fork 0
/
143. Reorder list
52 lines (41 loc) · 1.12 KB
/
143. Reorder list
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
//143. Reorder list
public class ListNode {
int val;
ListNode next;
ListNode() {}
ListNode(int val) { this.val = val; }
ListNode(int val, ListNode next) { this.val = val; this.next = next; }
}
class Solution {
public void reorderList(ListNode head) {
ListNode slowp = head;
ListNode fastp = head;
while(fastp.next != null && fastp.next.next != null) {
fastp = fastp.next.next;
slowp = slowp.next;
}
ListNode head2 = reverse(slowp);
slowp.next = null;
while(head != null && head2 != null) {
ListNode temp1 = head.next;
ListNode temp2 = head2.next;
head.next = head2;
head2.next = temp1;
head = temp1;
head2 = temp2;
}
}
static ListNode reverse(ListNode head) {
ListNode curr = head;
ListNode prev = null;
ListNode next = null;
while(curr != null) {
next = curr.next;
curr.next = prev;
prev = curr;
curr = next;
}
head = prev;
return head;
}
}