-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path143.go
60 lines (51 loc) · 964 Bytes
/
143.go
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
package p143
/**
Given a singly linked list L: L0→L1→…→Ln-1→Ln,
reorder it to: L0→Ln→L1→Ln-1→L2→Ln-2→…
You must do this in-place without altering the nodes' values.
For example,
Given {1,2,3,4}, reorder it to {1,4,2,3}.
*/
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
type ListNode struct {
Val int
Next *ListNode
}
func reorderList(head *ListNode) {
if head == nil || head.Next == nil {
return
}
master := &ListNode{0, head}
slow, quick := master, head
for quick != nil {
slow = slow.Next
quick = quick.Next
if quick != nil {
quick = quick.Next
}
}
quick = slow.Next
slow.Next = nil
cur := quick.Next
quick.Next = nil
for cur != nil {
tmp := cur
cur = cur.Next
tmp.Next = quick
quick = tmp
}
slow = head
for quick != nil {
tmp := quick
quick = quick.Next
tmp.Next = slow.Next
slow.Next = tmp
slow = tmp.Next
}
}