-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmergeKSortedLists.go
93 lines (85 loc) · 1.48 KB
/
mergeKSortedLists.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
91
92
93
//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 mergeKLists(lists []*Node) *Node {
n := len(lists)
if n == 0 {
return nil
}
if n == 1 {
return lists[0]
}
left := mergeKLists(lists[:n/2])
right := mergeKLists(lists[n/2:])
return mergeTwoLists(left, right)
}
func mergeTwoLists(list1, list2 *Node) *Node {
dummy := &Node{}
curr := dummy
for list1 != nil && list2 != nil {
if list1.Value < list2.Value {
curr.Next = list1
list1 = list1.Next
} else {
curr.Next = list2
list2 = list2.Next
}
curr = curr.Next
}
if list1 != nil {
curr.Next = list1
}
if list2 != nil {
curr.Next = list2
}
return dummy.Next
}
func main() {
lists1 := []*Node{
build([]int{1, 2, 4}),
build([]int{1, 3, 5}),
build([]int{3, 6}),
}
mergedHead1 := mergeKLists(lists1)
traverse(mergedHead1)
lists2 := []*Node{
build([]int{}),
build([]int{}),
}
mergedHead2 := mergeKLists(lists2)
traverse(mergedHead2)
lists3 := []*Node{
build([]int{}),
}
mergedHead3 := mergeKLists(lists3)
traverse(mergedHead3)
}