-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathreorder-list.go
90 lines (80 loc) · 1.53 KB
/
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
package main
import (
"fmt"
"bytes"
)
type ListNode struct {
Val int
Next *ListNode
}
func (head *ListNode) String() string {
var buf = bytes.Buffer{}
for n := head; n != nil; n = n.Next {
if n != head {
buf.WriteString(" -> ")
}
buf.WriteString(fmt.Sprintf("[%d]", n.Val))
}
return buf.String()
}
func reorderList(head *ListNode) {
if head == nil || head.Next == nil {
return
}
length := 0
tail := head
for n := head; n != nil; n = n.Next {
if n.Next == nil {
tail = n
}
length++
}
firstTail := head
for n, i := head, 1; i <= length; i++ {
if i == length/2 {
firstTail = n
}
n = n.Next
}
secondHead := firstTail.Next
firstTail.Next = nil
secondHead, tail = doReverse(secondHead, tail)
for left, right := head, secondHead; right != nil; {
nextRight := right.Next
right.Next = left.Next
left.Next = right
if right.Next != nil {
left = right.Next
} else {
left = right
}
right = nextRight
}
}
func doReverse(head, tail *ListNode) (*ListNode, *ListNode) {
if head == nil || tail == nil || head == tail {
return tail, head
}
pre, cur, next := head, head.Next, head.Next.Next
for {
cur.Next = pre
if cur == tail {
break
}
pre = cur
cur = next
next = next.Next
}
head.Next = nil
return tail, head
}
func main() {
h := &ListNode{1, &ListNode{2, &ListNode{3, &ListNode{4, &ListNode{5, nil}}}}}
hh := &ListNode{1, &ListNode{2, &ListNode{3, &ListNode{4, nil}}}}
fmt.Print(h)
reorderList(h)
fmt.Println("\t", h)
fmt.Print(hh)
reorderList(hh)
fmt.Println("\t", hh)
}