package main
import (
"container/heap"
"fmt"
)
// ListNode defines a node in a singly linked list
// It holds an integer value and a pointer to the next node
// This is the basic building block of our lists
type ListNode struct {
Val int
Next *ListNode
}
// MinHeap implements heap.Interface for []*ListNode based on node values
// This allows us to always get the smallest node efficiently
type MinHeap []*ListNode
func (h MinHeap) Len() int { return len(h) }
func (h MinHeap) Less(i, j int) bool { return h[i].Val < h[j].Val }
func (h MinHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] }
func (h *MinHeap) Push(x interface{}) {
// Add new node to heap
*h = append(*h, x.(*ListNode))
}
func (h *MinHeap) Pop() interface{} {
// Remove smallest node from heap
n := len(*h)
x := (*h)[n-1]
*h = (*h)[:n-1]
return x
}
// mergeKLists merges k sorted linked lists into one sorted list
// It uses a min heap to always pick the smallest current node
func mergeKLists(lists []*ListNode) *ListNode {
minHeap := &MinHeap{}
heap.Init(minHeap)
// Insert first node of each list into min heap
for _, node := range lists {
if node != nil {
heap.Push(minHeap, node)
}
}
dummy := &ListNode{} // Dummy head for merged list
current := dummy
// Extract min node and add next node from same list to heap
for minHeap.Len() > 0 {
minNode := heap.Pop(minHeap).(*ListNode) // smallest node
current.Next = minNode
current = current.Next
if minNode.Next != nil {
heap.Push(minHeap, minNode.Next) // add next node to heap
}
}
return dummy.Next
}
// Helper to print linked list
func printList(head *ListNode) {
for head != nil {
fmt.Printf("%d -> ", head.Val)
head = head.Next
}
fmt.Println("null")
}
func main() {
// Create example lists: [1->4->7], [2->5->8], [3->6->9]
l1 := &ListNode{1, &ListNode{4, &ListNode{7, nil}}}
l2 := &ListNode{2, &ListNode{5, &ListNode{8, nil}}}
l3 := &ListNode{3, &ListNode{6, &ListNode{9, nil}}}
merged := mergeKLists([]*ListNode{l1, l2, l3})
printList(merged)
}
for _, node := range lists {
if node != nil {
heap.Push(minHeap, node)
}
}
Insert first nodes of all lists into min heap to start merging
for minHeap.Len() > 0 {
minNode := heap.Pop(minHeap).(*ListNode)
current.Next = minNode
current = current.Next
if minNode.Next != nil {
heap.Push(minHeap, minNode.Next)
}
}
Repeatedly extract smallest node and add its next node to heap to maintain sorted order
1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7 -> 8 -> 9 -> null