-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathreorderList.go
72 lines (65 loc) · 1.26 KB
/
reorderList.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
//go:build ignore
package main
import "fmt"
type Node struct {
Value int
Next *Node
}
func build(arr []int) *Node {
var head *Node
for i := len(arr) - 1; i >= 0; i-- {
head = &Node{Value: arr[i], Next: head}
}
return head
}
func traverse(head *Node) {
if head == nil {
fmt.Println("The list is empty.")
return
}
current := head
for current != nil {
if current.Next != nil {
fmt.Print(current.Value, "->")
} else {
fmt.Print(current.Value)
}
current = current.Next
}
fmt.Println()
}
func reorderList(head *Node) {
slow, fast := head, head
for fast != nil && fast.Next != nil {
slow = slow.Next
fast = fast.Next.Next
}
secondHalf := slow.Next
slow.Next = nil
var prevSecondHalf *Node
for secondHalf != nil {
next := secondHalf.Next
secondHalf.Next = prevSecondHalf
prevSecondHalf = secondHalf
secondHalf = next
}
first := head
secondHalf = prevSecondHalf
for secondHalf != nil {
nextFirst, nextSecond := first.Next, secondHalf.Next
first.Next = secondHalf
secondHalf.Next = nextFirst
first = nextFirst
secondHalf = nextSecond
}
}
func main() {
arr1 := []int{2, 4, 6, 8}
head1 := build(arr1)
reorderList(head1)
traverse(head1)
arr2 := []int{2, 4, 6, 8, 10}
head2 := build(arr2)
reorderList(head2)
traverse(head2)
}