티스토리 뷰
문제
정렬된 두 개의 링크된 list1
과 list2
의 head가 주어진다.
두 목록을 하나의 정렬된 list로 병합
하고, 병합된 list의 헤드를 반환
한다.
leetcode 21 - Merge Two Sorted Lists
코드
# 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]:
# list1과 list2를 비교하여, 더 작은 값이 왼쪽에 오도록 한다.
if (not list1) or (list2 and (list1.val > list2.val)):
list1, list2 = list2, list1 # Python 다중 할당
# list1의 next를 재귀호출 하며 다음번 연결 리스트가 계속 스왑될 수 있도록 한다.
if list1:
list1.next = self.mergeTwoLists(list1.next, list2)
return list1
'알고리즘' 카테고리의 다른 글
[algorithm] leetcode 24 - Swap Nodes in Pairs (파이썬) (0) | 2022.03.17 |
---|---|
[algorithm] leetcode 206 - Reverse Linked List (파이썬) (0) | 2022.03.16 |
[algorithm] leetcode 121 - Best Time to Buy and Sell Stock (파이썬) (0) | 2022.03.14 |
[algorithm] leetcode 1 - Two Sum (파이썬) (0) | 2022.03.12 |
[algorithm] leetcode 937 - Reorder Data in Log Files (파이썬) (0) | 2022.03.11 |
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- 백준
- 문자열
- 스프링
- Spring
- 자료구조
- 파이썬
- mysql 8.0
- MySQL
- 리팩토링
- 스프링 부트
- webflux
- 릿코드
- leetcode
- 김영한
- Algorithm
- 노마드코더
- 코테
- 정렬
- 코틀린
- 알고리즘
- 데이터베이스
- Real MySQL
- spring boot
- 노마드
- 스프링부트
- 그리디
- 북클럽
- 인프런
- 구현
- kotlin
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 |
글 보관함