Skip to content

Commit bcabb5c

Browse files
Merge pull request #4 from Pal-Sandeep/3-merge-two-shorted-list
📦 NEW: merge_two_shorted_list
2 parents c938f06 + dc7603d commit bcabb5c

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed

021_Merge_Two_Shorted_List.py

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
# Definition for singly-linked list.
2+
class ListNode:
3+
def __init__(self, x):
4+
self.val = x
5+
self.next = None
6+
7+
def __repr__(self):
8+
if self:
9+
return "{} -> {}".format(self.val, self.next)
10+
11+
12+
class Solution:
13+
def mergeTwoLists(self, l1, l2):
14+
dummy = ListNode(0)
15+
current = dummy
16+
17+
while l1 and l2:
18+
if l1.val < l2.val:
19+
current.next = l1
20+
l1 = l1.next
21+
else:
22+
current.next = l2
23+
l2 = l2.next
24+
current = current.next
25+
26+
if l1:
27+
current.next = l1
28+
else:
29+
current.next = l2
30+
31+
return dummy.next
32+
33+
34+
if __name__ == "__main__":
35+
l1 = ListNode(0)
36+
l1.next = ListNode(1)
37+
l2 = ListNode(2)
38+
l2.next = ListNode(3)
39+
print(Solution().mergeTwoLists(l1, l2))

0 commit comments

Comments
 (0)