题解 | #合并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
}

全部评论

相关推荐

不愿透露姓名的神秘牛友
昨天 18:54
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务