23.合并K个升序链表
23.合并K个升序链表
题解
没啥含金量,就更归并排序一样,考验基本功吧
代码
type ListNode struct { Val int Next *ListNode } func mergeKLists(lists []*ListNode) *ListNode { dummy := &ListNode{} for _, v := range lists { dummy.Next = merge(dummy.Next, v) } return dummy.Next } func merge(l1, l2 *ListNode) *ListNode { dummy := &ListNode{} cur := dummy for l1 != nil && l2 != nil { if l1.Val <= l2.Val { cur.Next = l1 l1 = l1.Next } else { cur.Next = l2 l2 = l2.Next } cur = cur.Next } for l1 != nil { cur.Next = l1 l1 = l1.Next cur = cur.Next } for l2 != nil { cur.Next = l2 l2 = l2.Next cur = cur.Next } return dummy.Next }