| 일 | 월 | 화 | 수 | 목 | 금 | 토 |
|---|---|---|---|---|---|---|
| 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 |
Tags
- GenerativeAI
- 알고리즘
- BFS
- graph
- sql코테
- 리트코드
- two-pointer
- 코드업
- GenAI
- 파이썬알고리즘
- Greedy
- dfs
- 생성형AI
- Python3
- SQL
- codeup
- 릿코드
- stratascratch
- 슬라이딩윈도우
- array
- heap
- nlp
- 투포인터
- Python
- binary Tree
- 니트코드
- 파이썬
- Stack
- LeetCode
- tree
Archives
- Today
- Total
Tech for good
[Neetcode/Linked List] Merge Two Sorted Linked Lists 본문
IT/Computer Science
[Neetcode/Linked List] Merge Two Sorted Linked Lists
Diana Kang 2025. 6. 2. 12:59https://neetcode.io/problems/merge-two-sorted-linked-lists?list=neetcode150
NeetCode
neetcode.io


# 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]:
# Dummy node to simplify the merging logic
dummy = ListNode()
current = dummy
# Iterate over both lists while both have nodes
while list1 and list2:
if list1.val <= list2.val:
current.next = list1
list1 = list1.next
else:
current.next = list2
list2 = list2.next
current = current.next
# Append the rest of the remaining list
if list1:
current.next = list1
else:
current.next = list2
# Return the merged list (starting after dummy)
return dummy.next