Skip to content

Commit

Permalink
improved previous solution, shorter. Found a solution that has the sa…
Browse files Browse the repository at this point in the history
…me time and space complexity but it is shorter. I think I might want to practice this one to save time. -@iamserda
  • Loading branch information
iamserda committed Jan 31, 2025
1 parent 6c8d8ed commit f201ca7
Show file tree
Hide file tree
Showing 2 changed files with 57 additions and 33 deletions.
50 changes: 17 additions & 33 deletions neetcodeio/algostructybeginners/Lv2-LinkedLists/mergesinglylist.py
Original file line number Diff line number Diff line change
@@ -1,55 +1,39 @@
# Definition for singly-linked list.
"""
Problem:
Given the head pointer to two sorted linked list, merge the two sorted linked-list,
to result in a sorted linked. return the head of the newly sorted linked-list.
"""

class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next


class Solution:
def mergeTwoLists(self, list1: ListNode, list2: ListNode) -> ListNode:
if not list1 and not list2:
return None
if not list1:
return list2
if not list2:
return list1

def mergeTwoLists(self, list1: ListNode, list2: ListNode) -> ListNode:
pre = ListNode(-1)
current = pre
temp1 = list1
temp2 = list2
while temp1 or temp2:
if temp1:
if temp2:
if temp1.val <= temp2.val:
node = temp1
temp1 = temp1.next
node.next = None
current.next = node
current = current.next
continue
node = temp2
temp2 = temp2.next
node.next = None
current.next = node
current = current.next
continue
node = temp1
while temp1 and temp2:
if temp1.val <= temp2.val:
current.next = temp1
temp1 = temp1.next
node.next = None
current.next = node
current = current.next
continue
if temp2:
node = temp2
current.next = None
else:
current.next = temp2
temp2 = temp2.next
node.next = None
current.next = node
current = current.next
continue
current.next = None
if temp1 or temp2:
current.next = temp1 if temp1 else temp2
return pre.next if pre.next else None


# TESTING ARENA:
s1 = ListNode(11)
s1.next = ListNode(32)
s1.next.next = ListNode(53)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next


class Solution:
def mergeTwoLists(self, list1, list2):
cur = dummy = ListNode()
while list1 and list2:
if list1.val < list2.val:
cur.next = list1
list1, cur = list1.next, list1
else:
cur.next = list2
list2, cur = list2.next, list2

if list1 or list2:
cur.next = list1 if list1 else list2

return dummy.next


# TESTING ARENA:
s1 = ListNode(11)
s1.next = ListNode(32)
s1.next.next = ListNode(53)

s2 = ListNode(20)
s2.next = ListNode(41)
s2.next = ListNode(63)

# Testing:
sol = Solution()
singly = sol.mergeTwoLists(s1, s2)
answer = []
while singly:
answer.append(singly.val)
singly = singly.next
print(answer)

0 comments on commit f201ca7

Please sign in to comment.