package main
import "fmt"
type ListNode struct {
Val int
Next *ListNode
}
// 创建链表
func createList(nums []int) *ListNode {
head := &ListNode{}
tail := head
for i := 0; i < len(nums); i++ {
node := &ListNode{Val: nums[i]}
tail.Next = node
tail = node
}
return head.Next
}
// 打印链表
func printList(head *ListNode) {
for p := head.Next; p != nil; p = p.Next {
fmt.Printf("%d ", p.Val)
}
fmt.Println()
}
func mergeTwoLists(list1 *ListNode, list2 *ListNode) *ListNode {
newList := &ListNode{}
tail := newList
for list1 != nil && list2 != nil {
if list1.Val < list2.Val {
tail.Next = list1
tail = list1
list1 = list1.Next
} else {
tail.Next = list2
tail = list2
list2 = list2.Next
}
}
if list1 != nil {
tail.Next = list1
} else {
tail.Next = list2
}
return newList.Next
}
func main() {
list1 := createList([]int{0, 2, 4})
list2 := createList([]int{1, 5, 6})
list := mergeTwoLists(list1, list2)
printList(list)
}
标签:ListNode,21,Val,list1,Next,链表,tail,有序,list2
From: https://www.cnblogs.com/gdut17code/p/18237259