반응형
Notice
Recent Posts
Recent Comments
- Today
- Total
작심삼일
[LeetCode] 21 | Merge Two Sorted Lists | Python 본문
728x90
반응형
문제 링크: https://leetcode.com/problems/merge-two-sorted-lists/
문제
You are given the heads of two sorted linked lists list1 and list2.
Merge the two lists in a one sorted list. The list should be made by splicing together the nodes of the first two lists.
Return the head of the merged linked list.
조건
- The number of nodes in both lists is in the range [0, 50].
- -100 <= Node.val <= 100
- Both list1 and list2 are sorted in non-decreasing order.
내 풀이
list1과 list2의 현재 val을 비교하며 더 작은 것을 head에 추가한다.
코드
# 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]:
ans = ListNode()
head = ans
while list1 or list2:
if list1 and list2:
if list1.val < list2.val:
head.next = ListNode(list1.val)
list1 = list1.next if list1.next else None
else:
head.next = ListNode(list2.val)
list2 = list2.next if list2.next else None
elif list1:
head.next = ListNode(list1.val)
list1 = list1.next if list1.next else None
elif list2:
head.next = ListNode(list2.val)
list2 = list2.next if list2.next else None
head = head.next
return ans.next
728x90
반응형
'스터디 > 코테' 카테고리의 다른 글
[LeetCode] 2 | Add Two Numbers | Python (0) | 2022.03.10 |
---|---|
[LeetCode] 141 | Linked List Cycle | Python (0) | 2022.03.08 |
[LeetCode] 799 | Champagne Tower | Python (0) | 2022.03.04 |
[LeetCode] 413 | Arithmetic Slices | Python (0) | 2022.03.03 |
[LeetCode] 392 | Is Subsequence | Python (0) | 2022.03.02 |
Comments