Skip to content

Instantly share code, notes, and snippets.

@viveksyngh
Created October 2, 2015 09:20
Show Gist options
  • Select an option

  • Save viveksyngh/9112ca7c6bd89fac97c5 to your computer and use it in GitHub Desktop.

Select an option

Save viveksyngh/9112ca7c6bd89fac97c5 to your computer and use it in GitHub Desktop.
Merge k sorted linked lists and return it as one sorted list.
__author__ = 'Vivek'
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
import heapq
class Solution:
# @param A : list of linked list
# @return the head node in the linked list
def mergeKLists(self, A):
if len(A) == 0 :
return []
heap = []
res = ListNode(0)
temp = res
for i in range(len(A)) :
if A[i] :
heapq.heappush(heap,( A[i].val, i))
while heap :
val, i = heapq.heappop(heap)
temp.next = A[i]
A[i] = A[i].next
temp = temp.next
if A[i] :
heapq.heappush(heap, (A[i].val, i))
temp.next = None
return res.next
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment