-
Notifications
You must be signed in to change notification settings - Fork 3
/
solution.go
59 lines (51 loc) · 955 Bytes
/
solution.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
package main
import "fmt"
// ListNode is a singly-linked list.
type ListNode struct {
Val int
Next *ListNode
}
func mergeTwoLists(l1 *ListNode, l2 *ListNode) *ListNode {
// return the other linked list if nil
if l1 == nil {
return l2
}
if l2 == nil {
return l1
}
// find the link list started with smaller node
// set the first node as head
var head, node *ListNode
if l1.Val < l2.Val {
head = l1
node = l1
l1 = l1.Next
} else {
head = l2
node = l2
l2 = l2.Next
}
// loop through l1 and l2
// shift to the next node
for l1 != nil && l2 != nil {
if l1.Val < l2.Val {
l1, node.Next = l1.Next, l1
} else {
l2, node.Next = l2.Next, l2
}
node = node.Next
}
// if one of the link lists ended, link to the other one
if l1 != nil {
node.Next = l1
}
if l2 != nil {
node.Next = l2
}
return head
}
func main() {
l1 := &ListNode{1, nil}
l2 := &ListNode{2, nil}
fmt.Println(mergeTwoLists(l1, l2))
}