|
| 1 | +""" |
| 2 | +[Problem] |
| 3 | +https://leetcode.com/problems/merge-two-sorted-lists/description/ |
| 4 | +
|
| 5 | +두 정렬된 링크드 리스트의 Head가 주어진다. |
| 6 | +두 리스트를 하나의 정렬된 리스트로 합치시오. |
| 7 | +merged linked list의 Head를 반환하자. |
| 8 | +
|
| 9 | +[Brainstorming] |
| 10 | +두 개의 Sorted Linked Listd의 Head가 주어졌을 떄, 이미 정렬이 되어 있기 떄문에 |
| 11 | +반복문을 총 2번 순회하여 하나의 Merged Linked List를 만들 수 있다. |
| 12 | +
|
| 13 | +[Complexity] |
| 14 | +N: list1.length, M: list2.length |
| 15 | +Time: O(N + M) |
| 16 | +Space: O(N + M) |
| 17 | +
|
| 18 | +[Todo] |
| 19 | +- 재귀적으로 풀어보기. |
| 20 | +
|
| 21 | +""" |
| 22 | +from typing import Optional, List |
| 23 | + |
| 24 | + |
| 25 | +# Definition for singly-linked list. |
| 26 | +class ListNode: |
| 27 | + def __init__(self, val=0, next=None): |
| 28 | + self.val = val |
| 29 | + self.next = next |
| 30 | + |
| 31 | +class Solution: |
| 32 | + def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]: |
| 33 | + dummy_head = ListNode(0) |
| 34 | + current_node = dummy_head |
| 35 | + while list1 and list2: |
| 36 | + if list1.val > list2.val: |
| 37 | + current_node.next = ListNode(list2.val) |
| 38 | + list2 = list2.next |
| 39 | + else: |
| 40 | + current_node.next = ListNode(list1.val) |
| 41 | + list1 = list1.next |
| 42 | + current_node = current_node.next |
| 43 | + |
| 44 | + current_node.next = list1 or list2 |
| 45 | + |
| 46 | + return dummy_head.next |
| 47 | + |
| 48 | + |
| 49 | +def generate(list:List[int])->Optional[ListNode]: |
| 50 | + dummy_head = ListNode(0) |
| 51 | + current_node = dummy_head |
| 52 | + for x in list: |
| 53 | + current_node.next = ListNode(x) |
| 54 | + current_node = current_node.next |
| 55 | + return dummy_head.next |
| 56 | + |
| 57 | +def print_list(node:Optional[ListNode])->None: |
| 58 | + list = [] |
| 59 | + while node: |
| 60 | + list.append(node.val) |
| 61 | + node = node.next |
| 62 | + print(list) |
| 63 | + |
| 64 | +sol = Solution() |
| 65 | +print_list(sol.mergeTwoLists(generate([1,2,4]), generate([1,3,4]))) |
| 66 | + |
| 67 | + |
0 commit comments