题解 | #合并k个已排序的链表#
合并k个已排序的链表
https://www.nowcoder.com/practice/65cfde9e5b9b4cf2b6bafa5f3ef33fa6
package main import . "nc_tools" /* * type ListNode struct{ * Val int * Next *ListNode * } */ /** * * @param lists ListNode类一维数组 * @return ListNode类 */ func mergeKLists(lists []*ListNode) *ListNode { return mergeKList(lists, 0, len(lists)-1) } func mergeKList(lists []*ListNode, st int, en int) *ListNode { if st > en { return nil } if st == en { return lists[st] } mid := (st + en) / 2 left := mergeKList(lists, st, mid) right := mergeKList(lists, mid+1, en) return mergeL(left, right) } func mergeL(left *ListNode, right *ListNode) *ListNode { var head *ListNode var m *ListNode p := left q := right for p != nil || q != nil { if p == nil || (q != nil && p.Val >= q.Val) { if m == nil { m = q head = m } else { m.Next = q m = q } q = q.Next continue } if q == nil || (p != nil && p.Val < q.Val) { if m == nil { m = p head = m } else { m.Next = p m = p } p = p.Next } } return head }