-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
0143-reorder-list.cs
62 lines (52 loc) · 1.44 KB
/
0143-reorder-list.cs
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
53
54
55
56
57
58
59
60
61
62
/**
* Definition for singly-linked list.
* public class ListNode {
* public int val;
* public ListNode next;
* public ListNode(int val=0, ListNode next=null) {
* this.val = val;
* this.next = next;
* }
* }
*/
public class Solution {
private ListNode revList(ListNode head) {
ListNode prev = null;
var cur = head;
while(cur != null) {
var temp = cur.next;
cur.next = prev;
prev = cur;
cur = temp;
}
return prev;
}
public void ReorderList(ListNode head) {
if(head == null || head.next == null) return;
// find middle
var slow = head;
var fast = head.next;
var nodeCount = 1;
while(true) {
if(fast == null || fast.next == null) break;
slow = slow.next;
nodeCount++;
fast = fast.next.next;
}
var middle = slow.next;
slow.next = null;
var secondHead = revList(middle);
// merge two lists
var first = head;
var second = secondHead;
while(second != null) {
var temp1 = first.next;
var temp2 = second.next;
first.next = second;
second.next = temp1;
first = temp1;
second = temp2;
}
return;
}
}