| 일 | 월 | 화 | 수 | 목 | 금 | 토 |
|---|---|---|---|---|---|---|
| 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
- SQL
- heap
- Python
- BFS
- array
- LeetCode
- GenAI
- binary Tree
- graph
- two-pointer
- 생성형AI
- 니트코드
- sql코테
- stratascratch
- GenerativeAI
- Greedy
- 파이썬알고리즘
- 알고리즘
- 코드업
- tree
- Python3
- 투포인터
- nlp
- dfs
- 리트코드
- 파이썬
- 슬라이딩윈도우
- Stack
- codeup
- 릿코드
Archives
- Today
- Total
Tech for good
[Neetcode/Linked List] Reorder Linked List 본문


# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def reorderList(self, head: Optional[ListNode]) -> None:
"""
Do not return anything, modify head in-place instead.
"""
# 1. Find the middle of the list (slow & fast pointer)
slow = head
fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
# 2. Reverse the second half of the list
prev = None # Initialize prev pointer for reversal
curr = slow.next # Start of the second half
slow.next = None # Split the list into two halves
# Reverse the second half in-place
while curr:
next_node = curr.next # Store next node
curr.next = prev # Reverse the link
prev = curr # Move prev forward
curr = next_node # Move curr forward
# 3. Merge two halves: first half and reversed second half
first = head # Pointer to start of first half
second = prev # Pointer to start of first half
while second:
tmp1 = first.next
tmp2 = second.next
first.next = second
second.next = tmp1
first = tmp1
second = tmp2'IT > Computer Science' 카테고리의 다른 글
| [Leetcode/Linked List, Hash Table] 3063. Linked List Frequency (0) | 2025.07.13 |
|---|---|
| [Leetcode/Linked List]83. Remove Duplicates from Sorted List (0) | 2025.07.12 |
| [Neetcode/Linked List] Remove Node From End of Linked List (4) | 2025.07.10 |
| [Leetcode/Linked List, Two Pointers] 876. Middle of the Linked List (0) | 2025.07.09 |
| [Neetcode/Linked Lists] Intersection of Two Linked Lists (0) | 2025.07.03 |