मान लीजिए हमारे पास कुछ सूचियाँ हैं, ये सॉर्टेड हैं। हमें इन सूचियों को एक सूची में मर्ज करना है। इसे हल करने के लिए, हम हीप डेटा संरचना का उपयोग करेंगे। इसलिए यदि सूचियाँ [1,4,5], [1,3,4], [2,6] हैं, तो अंतिम सूची [1,1,2,3,4,4,5,6] होगी।
इसे हल करने के लिए, हम इन चरणों का पालन करेंगे −
एक हीप बनाएं
lists में प्रत्येक लिंक्ड सूची l के लिए −
यदि l 0 नहीं है, तो l को हीप में डालें
res := null और res_next := null
एक अनंत लूप करें −
temp := हीप का न्यूनतम
यदि हीप में कोई तत्व नहीं है, तो res लौटाएं
यदि res 0 है, तो
res := temp, res_next := temp
temp := temp का अगला तत्व
यदि temp शून्य नहीं है, तो temp को हीप में डालें
res का अगला := null
अन्यथा −
res_next का अगला := temp, temp := temp का अगला, res_next := res_next का अगला
यदि temp null नहीं है, तो temp को हीप में डालें
res_next का अगला := null
उदाहरण
बेहतर समझ के लिए निम्नलिखित कार्यान्वयन देखें −
class ListNode: def __init__(self, data, next = None): self.val = data self.next = next def make_list(elements): head = ListNode(elements[0]) for element in elements[1:]: ptr = head while ptr.next: ptr = ptr.next ptr.next = ListNode(element) return head def print_list(head): ptr = head print('[', end = "") while ptr: print(ptr.val, end = ", ") ptr = ptr.next print(']') class Heap: def __init__(self): self.arr = [] def print_heap(self): res = " " for i in self.arr: res += str(i.val) + " " print(res) def getVal(self,i): return self.arr[i].val def parent(self,i): return (i-1)//2 def left(self,i): return (2*i + 1) def right(self,i): return (2*i + 2) def insert(self,value): self.arr.append(value) n = len(self.arr)-1 i = n while i != 0 and self.arr[i].valइनपुट
[[1,4,5],[1,3,4],[2,6]]
आउटपुट
[1, 1, 2, 3, 4, 4, 5, 6, ]