one line of code at a time
[leetcode] 21. Merge Two Sorted Lists 파이썬 코드 본문
https://leetcode.com/problems/merge-two-sorted-lists/
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution(object):
def mergeTwoLists(self, list1, list2):
dummy = ListNode()
tail = dummy # 더미 노드의 마지막을 가리키는 포인터
while list1 and list2: # while list1 and list2 are not null
if list1.val < list2.val:
tail.next = list1
list1 = list1.next
else:
tail.next = list2
list2 = list2.next
tail = tail.next
# 이 로직이 빠지면 안 됨
if list1: # list1 is not null
tail.next = list1
else:
tail.next = list2
return dummy.next
참고
'leetcode' 카테고리의 다른 글
| [leetcode] 345. Reverse Vowels of a String 파이썬 코드 (0) | 2024.08.12 |
|---|---|
| [leetcode] 1432. Kids With the Greatest Number of Candies 파이썬 코드 (0) | 2024.08.12 |
| [leetcode] 206. Reverse Linked List 파이썬 코드 (0) | 2024.08.11 |
| [leetcode] 215. Kth Largest Element in an Array 파이썬 코드 (0) | 2024.08.10 |
| [leetcode] 703. Kth Largest Element in a Stream 파이썬 코드 (0) | 2024.08.09 |