File tree Expand file tree Collapse file tree 1 file changed +30
-0
lines changed
Expand file tree Collapse file tree 1 file changed +30
-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 (self , list1 : Optional [ListNode ], list2 : Optional [ListNode ]) -> Optional [ListNode ]:
8+ # head of merged linked list를 반환해야 하므로 head를 임시로 생성
9+ head = ListNode ()
10+ pointer = head
11+
12+ # 정렬된 링크드 리스트이므로 하나라도 끝까지 pointer를 이동해서 None이 될때까지 loop
13+ # 시간복잡도 O(n), 공간복잡도 O(1)
14+ while list1 and list2 :
15+ # val 비교해서 next 지정
16+ if list1 .val <= list2 .val :
17+ pointer .next = list1
18+ list1 = list1 .next
19+ else :
20+ pointer .next = list2
21+ list2 = list2 .next
22+ # pointer도 next로 이동
23+ pointer = pointer .next
24+ # 남은 리스트의 경우 정렬되어 있으므로 그대로 연결
25+ if list1 :
26+ pointer .next = list1
27+ else :
28+ pointer .next = list2
29+
30+ return head .next
You can’t perform that action at this time.
0 commit comments