-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathreorder_list.go
76 lines (59 loc) · 1.26 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
package main
import (
"fmt"
"github.com/j3rrywan9/go-algorithms/linkedlist"
)
// Split a linked list in two halves
func splitList(head *linkedlist.Node) (*linkedlist.Node, *linkedlist.Node) {
runner, walker := head, head
for runner != nil && runner.Next != nil {
walker = walker.Next
runner = runner.Next.Next
}
middle := walker.Next
walker.Next = nil
return head, middle
}
func reverseList(head *linkedlist.Node) *linkedlist.Node {
var dummy *linkedlist.Node
for head != nil {
current := head
head = head.Next
current.Next = dummy
dummy = current
}
return dummy
}
// Merge two linked lists
func mergeLists(a, b *linkedlist.Node) *linkedlist.Node {
head, tail := a, a
a = a.Next
for b != nil {
tail.Next = b
tail = tail.Next
b = b.Next
if a != nil {
a, b = b, a
}
}
return head
}
// LeetCode OJ No. 143
func reorderList(head *linkedlist.Node) *linkedlist.Node {
if head == nil || head.Next == nil {
return head
}
a, b := splitList(head)
b = reverseList(b)
head = mergeLists(a, b)
return head
}
func main() {
myList := &linkedlist.Node{1, nil}
fmt.Println("Creating a 10-node linked list...")
myList.Create(10)
myList.Print()
fmt.Println("Reordering above linked list...")
head := reorderList(myList)
head.Print()
}