Skip to content

Commit d8243fe

Browse files
committed
feat: merge-two-sorted-lists 풀이 추가
1 parent fade13e commit d8243fe

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed

merge-two-sorted-lists/unpo88.py

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
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+
dummy = ListNode()
9+
head = dummy
10+
11+
while list1 and list2:
12+
if list1.val < list2.val:
13+
head.next = list1
14+
list1 = list1.next
15+
else:
16+
head.next = list2
17+
list2 = list2.next
18+
head = head.next
19+
20+
if list1:
21+
head.next = list1
22+
elif list2:
23+
head.next = list2
24+
25+
return dummy.next
26+
27+
"""
28+
================================================================================
29+
풀이 과정
30+
================================================================================
31+
32+
[1차 시도] Dummy Node 활용
33+
────────────────────────────────────────────────────────────────────────────────
34+
1. 작은 값을 가진 노드를 골라서 head에 연결하는 방식으로 문제를 풀어보자.
35+
2. 한 쪽 리스트가 비게 되면 남은 노드를 그냥 연결해주면 될 것 같음.
36+
37+
dummy = ListNode()
38+
head = dummy
39+
40+
while list1 and list2:
41+
if list1.val < list2.val:
42+
head.next = list1
43+
list1 = list1.next
44+
else:
45+
head.next = list2
46+
list2 = list2.next
47+
head = head.next
48+
49+
if list1:
50+
head.next = list1
51+
elif list2:
52+
head.next = list2
53+
54+
return dummy.next
55+
"""

0 commit comments

Comments
 (0)