Skip to content

Commit 89e9adb

Browse files
committed
solve: reorder list
1 parent dcfb736 commit 89e9adb

File tree

1 file changed

+63
-0
lines changed

1 file changed

+63
-0
lines changed

reorder-list/KwonNayeon.py

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
"""
2+
Constraints:
3+
- The number of nodes in the list is in the range [1, 5 * 10^4].
4+
- 1 <= Node.val <= 1000
5+
6+
Time Complexity: O(n)
7+
- 리스트를 한 번씩 순회하면서 알고리즘의 각 단계를 수행함
8+
9+
Space Complexity: O(1)
10+
- 정해진 개수의 변수 외에는 추가 공간을 사용하지 않음
11+
12+
풀이방법:
13+
1. 중간 지점 찾기
14+
- slow/fast 포인터를 사용하여 중간 지점 찾기
15+
2. 뒷부분 뒤집기
16+
- prev, curr 포인터로 링크드 리스트의 방향 전환
17+
- next_temp에 다음 노드를 저장한 후 방향 변경
18+
3. 앞부분과 뒷부분 합치기
19+
- 두 리스트의 시작점(first, second)부터 시작
20+
- temp1, temp2에 다음 노드 저장
21+
- 포인터들을 번갈아가며 연결함
22+
"""
23+
# Definition for singly-linked list.
24+
# class ListNode:
25+
# def __init__(self, val=0, next=None):
26+
# self.val = val
27+
# self.next = next
28+
class Solution:
29+
def reorderList(self, head: Optional[ListNode]) -> None:
30+
"""
31+
Do not return anything, modify head in-place instead.
32+
"""
33+
# 중간 지점 찾기
34+
slow = head
35+
fast = head
36+
while fast and fast.next:
37+
slow = slow.next
38+
fast = fast.next.next
39+
40+
# 뒷부분 뒤집기
41+
prev = None
42+
curr = slow.next
43+
slow.next = None
44+
while curr:
45+
next_temp = curr.next
46+
curr.next = prev
47+
prev = curr
48+
curr = next_temp
49+
50+
# 앞부분과 뒷부분 합치기
51+
first = head
52+
second = prev
53+
while second:
54+
temp1 = first.next
55+
temp2 = second.next
56+
57+
first.next = second
58+
second.next = temp1
59+
60+
first = temp1
61+
second = temp2
62+
63+

0 commit comments

Comments
 (0)