【LEETCODE】23. 合并 K 个升序链表

给你一个链表数组,每个链表都已经按升序排列。

请你将所有链表合并到一个升序链表中,返回合并后的链表。
解:
很经典的题目, 这次是为了熟悉Go的语法。在使用文档中的heap例程时候, pop函数返回的是一个any类型,需要做一次转化。
具体,为什么要写作interface{}, 暂时不深究了。 可以看见的的是Go的性能不错,用时只有4ms。

/**
 * Definition for singly-linked list.
 * type ListNode struct {
 *     Val int
 *     Next *ListNode
 * }
 */
 import "fmt"
 import "container/heap"
 var print = fmt.Println

 type ListHeap []*ListNode

func (h ListHeap) Len() int           { return len(h) }
func (h ListHeap) Less(i, j int) bool { return (*h[i]).Val < (*h[j]).Val }
func (h ListHeap) Swap(i, j int)      { h[i], h[j] = h[j], h[i] }

func (h *ListHeap) Push(x interface{}) {
	// Push and Pop use pointer receivers because they modify the slice's length,
	// not just its contents.
	*h = append(*h, x.(*ListNode))
}

func (h *ListHeap) Pop() interface{} {
	old := *h
	n := len(old)
	x := old[n-1]
	*h = old[0 : n-1]
	return x
}


func mergeKLists(lists []*ListNode) *ListNode {
    var guard *ListNode = &ListNode{Val: 0,  Next: nil}
    n := len(lists)
    var ptr = guard
    h := &ListHeap{}
    heap.Init(h)
    for i:= 0; i < n; i ++ {
        if lists[i] != nil {
            heap.Push(h, lists[i])
        }
    }

    for h.Len() > 0{
        ele := heap.Pop(h).(*ListNode)
        if (*ele).Next != nil {
            heap.Push(h, (*ele).Next)
        }
        ptr.Next = ele
        ptr = ptr.Next
    }  
    
    return guard.Next
}

你可能感兴趣的:(leetcode,链表,Go)