File tree Expand file tree Collapse file tree 1 file changed +58
-0
lines changed Expand file tree Collapse file tree 1 file changed +58
-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 mergeKLists (self , lists : List [Optional [ListNode ]]) -> Optional [ListNode ]:
8
+ # 분할정복(divide and conquer), 쉽지않음,다시볼것,다른방식풀이들찾아볼것.
9
+
10
+ # 빈 리스트일 경우 None 반환
11
+ if len (lists ) == 0 :
12
+ return None
13
+
14
+ # 두 개의 리스트 병합하는 함수
15
+ def merge (list1 , list2 ):
16
+ dummy = ListNode () # 시작노드
17
+ tail = dummy # dummy의 끝을 가리키는 포인터
18
+
19
+ # list1와 list2에 노드가 있을 동안 반복
20
+ while list1 and list2 :
21
+ # list1값과 list2값 중 더 작은 노드 값을 dummy에 추가
22
+ if list1 .val < list2 .val :
23
+ tail .next = list1
24
+ list1 = list1 .next
25
+ else :
26
+ tail .next = list2
27
+ list2 = list2 .next
28
+ tail = tail .next
29
+
30
+ # 남은 노드들 붙이기
31
+ if list1 :
32
+ tail .next = list1
33
+ if list2 :
34
+ tail .next = list2
35
+
36
+ # dummy의 다음이 병합 결과
37
+ return dummy .next
38
+
39
+ # 전체 리스트가 하나가 될 때까지 병합
40
+ while len (lists ) > 1 :
41
+ merged = []
42
+
43
+ # 리스트 두 개씩 병합하기
44
+ for i in range (0 , len (lists ), 2 ):
45
+ list1 = lists [i ]
46
+
47
+ if i + 1 < len (lists ):
48
+ list2 = lists [i + 1 ]
49
+ else :
50
+ list2 = None
51
+
52
+ merged .append (merge (list1 ,list2 ))
53
+
54
+ # 병합된 리스트로 업데이트
55
+ lists = merged
56
+
57
+ # 하나로 병합된 리스트 반환
58
+ return lists [0 ]
You can’t perform that action at this time.
0 commit comments