-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathreorder_list.go
More file actions
57 lines (45 loc) · 862 Bytes
/
reorder_list.go
File metadata and controls
57 lines (45 loc) · 862 Bytes
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
package leetcode
type ListNode struct {
Val int
Next *ListNode
}
func reorderList(head *ListNode) {
if head.Next == nil {
return
}
dummyHead := ListNode{0, head}
mid := findMid(&dummyHead)
left := head
right := mid.Next
mid.Next = nil
right = reverse(right)
weave(left, right)
}
func findMid(head *ListNode) *ListNode {
fast := head
slow := head
for fast.Next != nil && fast.Next.Next != nil {
fast = fast.Next.Next
slow = slow.Next
}
return slow
}
func reverse(head *ListNode) *ListNode {
var first *ListNode = nil
second := head
for second != nil {
third := second.Next
second.Next = first
first, second = second, third
}
return first
}
func weave(left, right *ListNode) {
curr := left
for right != nil {
curr_next := curr.Next
curr.Next = right
left, right = right.Next, curr_next
curr = curr.Next
}
}