코딩 테스트/leetcode
[leetcode 2024/02/13] 21. Merge Two Sorted Lists
미뿌감
2024. 2. 13. 14:03
728x90
https://leetcode.com/problems/merge-two-sorted-lists/description/
LeetCode - The World's Leading Online Programming Learning Platform
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
1. 접근 방법
이번 문제는 2개의 linked list를 오름차순으로 merge해서 출력하는 것이 목표이다.
node = ListNode(0)
을 통해 시작 노드를 설정해주었다.
이후 list1.val < list2.val 을 비교해서, 해당 syntax가 True 라면 node.next = list1으로 해주었다. else는 node.next = list2를 해주었다.
==을 고려해주지 않은 이유는 어짜피, 둘 중 하나 값을 넣으면 되기 때문이다. list1 노드의 1 을 먼저 넣든, list2 노드의 1을 먼저 넣든 상관이 없기 때문이다. 같은 1 이기 때문이다.
이후 list1 또는 list2 둘 중 하나가 None을 가리키게 된다면, 반복문을 멈추고, 남은 list 노드들을 node linked list 뒤에 붙여주었다.
node.next = list1 if list1 else list2
-> 이렇게 붙여주었다.
2. 코드
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:
node = ListNode(0)
head = node
while list1 and list2:
if list1.val < list2.val:
node.next = list1
list1 = list1.next
else:
node.next = list2
list2 = list2.next
node = node.next
node.next = list1 if list1 else list2
return head.next
728x90