-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
improved previous solution, shorter. Found a solution that has the sa…
…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
Showing
2 changed files
with
57 additions
and
33 deletions.
There are no files selected for viewing
50 changes: 17 additions & 33 deletions
50
neetcodeio/algostructybeginners/Lv2-LinkedLists/mergesinglylist.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
40 changes: 40 additions & 0 deletions
40
neetcodeio/algostructybeginners/Lv2-LinkedLists/mergesinglylist2.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |