golang heap堆写法 大顶堆排序结构体

leetcode 23 合并K个升序链表

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

请你将所有链表合并到一个升序链表中,返回合并后的链表。

《golang heap堆写法 大顶堆排序结构体》
核心:

  1. heap堆新建的需要是slice形式的才可以排序,即需要包装两层
  2. 需要注意结构体slice中元素是否是指针
/** * Definition for singly-linked list. * type ListNode struct { * Val int * Next *ListNode * } */

 import "container/heap"
func mergeKLists(lists []*ListNode) *ListNode { 
    n := len(lists)
    queue := &hpList{ }
    heap.Init(queue)
    for i:=0; i<n; i++{ 
        if lists[i]!=nil{ 
            heap.Push(queue, &hp{ lists[i].Val, lists[i]})
        }
    }
    head := &ListNode{ }
    tail := head
    for queue.Len()>0{ 
        temp := heap.Pop(queue).(*hp)
        tail.Next = temp.Ptr
        tail = tail.Next
        if temp.Ptr.Next!=nil{ 
            heap.Push(queue, &hp{ temp.Ptr.Next.Val, temp.Ptr.Next})
        }
    }
    return head.Next
}

type hp struct{ 
    Val int
    Ptr *ListNode
}

type hpList []*hp

func(h hpList) Len() int{ 
    return len(h)
}

func(h hpList) Less(i, j int) bool{ 
    return h[i].Val < h[j].Val
}

func(h hpList) Swap(i, j int) { 
    h[i], h[j] = h[j], h[i]
}

func(h *hpList) Push(x interface{ }){ 
    *h = append(*h, x.(*hp))
}

func(h *hpList) Pop() (x interface{ }){ 
    old := *h
    n := len(old)
    x = old[n-1]
    *h = old[:n-1]
    return 
}
    原文作者:农夫小田
    原文地址: https://blog.csdn.net/t949500898/article/details/120313438
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞