输入两个递增排序的链表,合并这两个链表并使新链表中的节点仍然是递增排序的。
示例1:
输入:1->2->4, 1->3->4
输出:1->1->2->3->4->4
限制:
0 <= 链表长度 <= 1000
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/he-bing-liang-ge-pai-xu-de-lian-biao-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
func mergeTwoLists(l1 *ListNode, l2 *ListNode) *ListNode {
var root = &ListNode{}
var tail = root
for l1 != nil || l2 != nil{
if l1 != nil && l2 != nil {
if l1.Val < l2.Val {
tail.Next = l1
l1 = l1.Next
}else {
tail.Next = l2
l2 = l2.Next
}
}else if l1 == nil {
tail.Next = l2
break
}else if l2 == nil {
tail.Next = l1
break
}
tail = tail.Next
}
return root.Next
}
package main
import "fmt"
type ListNode struct {
Val int
Next *ListNode
}
func main() {
list1 := []int{1,2,4}
list2 := []int{1,3,4,5,6,7}
l1 := createList(list1)
l2 := createList(list2)
root := mergeTwoLists(l1,l2)
printList(root)
}
func mergeTwoLists(l1 *ListNode, l2 *ListNode) *ListNode {
var root = &ListNode{}
var tail = root
for l1 != nil || l2 != nil{
if l1 != nil && l2 != nil {
if l1.Val < l2.Val {
tail.Next = l1
l1 = l1.Next
}else {
tail.Next = l2
l2 = l2.Next
}
}else if l1 == nil {
tail.Next = l2
break
}else if l2 == nil {
tail.Next = l1
break
}
tail = tail.Next
}
return root.Next
}
func createList(list []int) *ListNode {
root := &ListNode{Val:list[0]}
tail := root
for i:=1;i<len(list);i++ {
tail.Next = &ListNode{Val:list[i]}
tail = tail.Next
}
return root
}
func printList(root *ListNode){
for root != nil {
fmt.Println(root.Val)
root = root.Next
}
}