File tree Expand file tree Collapse file tree 1 file changed +36
-0
lines changed
Expand file tree Collapse file tree 1 file changed +36
-0
lines changed Original file line number Diff line number Diff line change 1+ # Definition for singly-linked list.
2+ # class ListNode:
3+ # def __init__(self, val=0, next=None):
4+ # self.val = val
5+ # self.next = next
6+ class Solution :
7+ def mergeTwoLists (
8+ self , list1 : Optional [ListNode ], list2 : Optional [ListNode ]
9+ ) -> Optional [ListNode ]:
10+ """
11+ Solution:
12+ 1) 리스트1 리스트2가 null 이 아닌 동안 list1, list2를 차례대로 줄세운다.
13+ 2) list1이 남으면 node.next = list1로 남은 리스트를 연결한다.
14+ 3) list2가 남으면 list2 를 연결한다.
15+
16+ Time: O(n)
17+ Space: O(1)
18+ """
19+ dummy = ListNode ()
20+ node = dummy
21+
22+ while list1 and list2 :
23+ if list1 .val < list2 .val :
24+ node .next = list1
25+ list1 = list1 .next
26+ else :
27+ node .next = list2
28+ list2 = list2 .next
29+ node = node .next
30+
31+ if list1 :
32+ node .next = list1
33+ elif list2 :
34+ node .next = list2
35+
36+ return dummy .next
You can’t perform that action at this time.
0 commit comments