forked from wufenggirl/LeetCode-in-Golang
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathreorder-list.go
executable file
·58 lines (48 loc) · 997 Bytes
/
reorder-list.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
package problem0143
import (
"github.com/aQuaYi/LeetCode-in-Go/kit"
)
type ListNode = kit.ListNode
func reorderList(head *ListNode) {
if head == nil {
return
}
// 获取 list 的长度 size
cur := head
size := 0
for cur != nil {
cur = cur.Next
size++
}
// size 为奇数, cur 指向 list 的中间节点
// size 为偶数, cur 指向 list 前一半的最后一个节点
cur = head
for i := 0; i < (size-1)/2; i++ {
cur = cur.Next
}
// head -> 1 -> 2 -> 3 -> 4 -> 5 -> 6
// ^
// |
// cur
// reverse cur 后面的 list
next := cur.Next
for next != nil {
temp := next.Next
next.Next = cur
cur = next
next = temp
}
end := cur
// head -> 1 -> 2 -> 3 <-> 4 <- 5 <- 6 <- end
// 从两头开始,整合链条
for head != end {
hNext := head.Next
eNext := end.Next
head.Next = end
end.Next = hNext
head = hNext
end = eNext
}
// 封闭 list, 避免出现环状 list
end.Next = nil
}