Skip to content

Commit 3ec0e59

Browse files
committed
[:solved #224]
1 parent 8220836 commit 3ec0e59

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

merge-two-sorted-lists/ppxyn1.py

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
# idea : Two Pointer
2+
# It was first time solving a two-pointer problem using nodes instead of arrays, and I realized I'm still not very familiar with nodes yet.
3+
class Solution:
4+
def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:
5+
dummy = ListNode(None)
6+
node = dummy
7+
while list1 and list2:
8+
if list1.val < list2.val:
9+
node.next = list1
10+
list1 = list1.next
11+
else:
12+
node.next = list2
13+
list2 = list2.next
14+
node = node.next
15+
node.next = list1 or list2
16+
return dummy.next
17+
18+
19+
# Another way to solve it
20+
# class Solution:
21+
# def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:
22+
# if not (list1 and list2):
23+
# return list1 or list2
24+
# if list1.val < list2.val:
25+
# list1.next = self.mergeTwoLists(list1.next, list2)
26+
# return list1
27+
# else:
28+
# list2.next = self.mergeTwoLists(list1, list2.next)
29+
# return list2
30+
31+

0 commit comments

Comments
 (0)