funcmergeTwoLists(l1 *ListNode, l2 *ListNode) *ListNode { var ( l *ListNode p *ListNode ) if l1 == nil && l2 == nil { returnnil } l = &ListNode{} p = l for l1 != nil || l2 != nil { if l1 == nil { p.Val = l2.Val l2 = l2.Next } elseif l2 == nil { p.Val = l1.Val l1 = l1.Next } elseif l1.Val > l2.Val { p.Val = l2.Val l2 = l2.Next } else { p.Val = l1.Val l1 = l1.Next } if l1 == nil && l2 == nil { p.Next = nil } else { p.Next = &ListNode{} p = p.Next } } return l }
本地测试
package main
import ( "fmt" )
type ListNode struct { Val int Next *ListNode }
funccreateListNode(a []int) *ListNode { var head *ListNode iflen(a) < 1 { return head } head = &ListNode{Val: a[0]} p := head a = a[1:] for _, item := range a { n := ListNode{Val: item} p.Next = &n p = p.Next } return head }
funcprintListNode(head *ListNode) { for head.Next != nil { fmt.Print(head.Val, " -> ") head = head.Next } if head != nil { fmt.Print(head.Val, "\n") } }
funcmain() { a, b := createListNode([]int{1, 2, 4}), createListNode([]int{1, 3, 4}) printListNode(a) printListNode(b) printListNode(mergeTwoLists(a, b)) }