Skip to content

Commit

Permalink
Create merge-k-lists.py
Browse files Browse the repository at this point in the history
Merges k sorted linked lists into one
  • Loading branch information
gabedonnan authored Jan 12, 2023
1 parent 70c8aee commit ec384b6
Showing 1 changed file with 54 additions and 0 deletions.
54 changes: 54 additions & 0 deletions merge-k-lists.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution(object):
def mergeKLists(self, lists):
"""
:type lists: List[ListNode]
:rtype: ListNode
"""
#print(lists)
final = ListNode(val = 0)
vals = {}
flag = True
while flag:
flag = False
for iterator,lis in enumerate(lists):
if lis != None:
flag = True
if lis.val not in vals.keys():
vals[lis.val] = 1
lists[iterator] = lis.next
else:
vals[lis.val] = vals[lis.val] + 1
lists[iterator] = lis.next
print(vals)
temp_li = self.unpack_dict(vals)
print(temp_li)
for item in temp_li:
self.add_to_end(item, final)
return final.next

def unpack_dict(self, input_dict):
flag = True
ordered_keys = sorted(input_dict)
temp = []
for item in ordered_keys:
while input_dict[item] != 0:
temp.append(ListNode(val=item))
input_dict[item] -= 1
return temp


def add_to_end(self, elem, linked_list):
temp = linked_list
while temp.next != None:
temp = temp.next
temp.next = elem





0 comments on commit ec384b6

Please sign in to comment.