File tree Expand file tree Collapse file tree 1 file changed +48
-3
lines changed Expand file tree Collapse file tree 1 file changed +48
-3
lines changed Original file line number Diff line number Diff line change 1
1
"""
2
2
[문제풀이]
3
3
# Inputs
4
-
4
+ - two sorted linked lists
5
5
# Outputs
6
-
6
+ - 두 링크드 리스트를 합쳐서 하나의 정렬된 (오름차순) 리스트 반환
7
7
# Constraints
8
-
8
+ - The number of nodes in both lists is in the range [0, 50].
9
+ - -100 <= Node.val <= 100
10
+ - Both list1 and list2 are sorted in non-decreasing order.
9
11
# Ideas
12
+ 두 링크드 리스트는 모두 오름차순으로 정렬되어 있음
13
+ -> ListNode는 val, next 로 되어있음
14
+
15
+ 우선 두 리스트 이어붙이고,
16
+ 먼가 리스트 정렬 알고리즘 써야할듯?
17
+ 리스트라서, 두 노드를 바꾸는 swap() 함수 쓰면서,
18
+ 왼쪽보다 오른쪽이 작으면 바꾸는 식으로 하면 될듯?
19
+
20
+ 즉, 붙어있는 두 노드 비교하면서 쭉 돌기
21
+ 하지만 인덱스가 없어서 어떻게 순회할지?
22
+ -> point라는 기준을 둬서 이 point를 기준으로 prev, next를 만들어서 순회
23
+ -> 근데 prev, next만으로는 swap이 어려워서 2개가 아닌 3개를 둬야할 것 같은데,
24
+ 구현 방법이 떠오르지 않아서 해설 참고
25
+
26
+ 해설 참고
27
+ - 기존 리스트 변경이 아닌, 아예 새로운 리스트를 재창조 하는 방식으로!
28
+
10
29
11
30
[회고]
31
+ 기존 리스트를 swap하려고 하다 보니, 어렵게 생각하게됨..
12
32
13
33
"""
14
34
15
35
36
+ # Definition for singly-linked list.
37
+ # class ListNode:
38
+ # def __init__(self, val=0, next=None):
39
+ # self.val = val
40
+ # self.next = next
41
+ class Solution :
42
+ def mergeTwoLists (self , list1 : Optional [ListNode ], list2 : Optional [ListNode ]) -> Optional [ListNode ]:
43
+
44
+ retList = ListNode (None )
45
+ head = retList
46
+
47
+ while list1 and list2 :
48
+ if list1 .val < list2 .val :
49
+ head .next = list1
50
+ list1 = list1 .next
51
+
52
+ else :
53
+ head .next = list2
54
+ list2 = list2 .next
55
+
56
+ head = head .next
57
+
58
+ head .next = list1 or list2
59
+ return retList .next
60
+
You can’t perform that action at this time.
0 commit comments