File tree Expand file tree Collapse file tree 1 file changed +31
-0
lines changed
Expand file tree Collapse file tree 1 file changed +31
-0
lines changed Original file line number Diff line number Diff line change 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+
You can’t perform that action at this time.
0 commit comments