Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
80 changes: 29 additions & 51 deletions reorder-list/KwonNayeon.py
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

코드의 동작 과정을 테스트 케이스를 활용해서 주석으로 꼼꼼하게 작성해주셔서 전체적인 코드 흐름을 파악하는데 많이 도움이 되는 것 같습니다. 이전에도 몇 번 코드 리뷰를 진행했던 적이 있었는데, 그때마다 꼼꼼하게 주석 및 풀이 도출 과정을 적으신 부분이 굉장히 인상적이었는데, 꾸준히 지속하시는 모습이 멋져요. :)

Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
- 포인터들을 번갈아가며 연결함

노트:
- 포인터 조작(연결리스트 뒤집기, 병합) 방법을 다 까먹어서 복습용 예시 주석을 추가해둠
- 포인터 조작(연결리스트 뒤집기, 병합)이 어려움. 스택 풀이도 준비해두기.
"""
# Definition for singly-linked list.
# class ListNode:
Expand All @@ -31,60 +31,38 @@
class Solution:
def reorderList(self, head: Optional[ListNode]) -> None:
# 초기 상태: 1->2->3->4->5

"""
Do not return anything, modify head in-place instead.
"""
# 1단계: 중간 지점 찾기
slow = head # slow = 1
fast = head # fast = 1
slow = head
fast = head

while fast and fast.next:
slow = slow.next # slow: 1->2->3
fast = fast.next.next # fast: 1->3->5->None
# 결과: slow는 3에 위치

slow = slow.next
fast = fast.next.next

# 2단계: 뒷부분 뒤집기
prev = None # prev = None
curr = slow.next # curr = 4 (뒷부분 시작점)
prev = None
curr = slow.next
slow.next = None # 분리: 1->2->3 | 4->5

while curr:
# 1회전: curr=4, prev=None
next_temp = curr.next # next_temp = 5
curr.next = prev # 4->None
prev = curr # prev = 4
curr = next_temp # curr = 5
# 상태: 1->2->3 | 4->None, curr=5

# 2회전: curr=5, prev=4
next_temp = curr.next # next_temp = None
curr.next = prev # 5->4
prev = curr # prev = 5
curr = next_temp # curr = None (종료)
# 상태: 1->2->3 | 5->4->None

next_temp = curr.next
curr.next = prev
prev = curr
curr = next_temp

# 3단계: 앞부분과 뒷부분 합치기
first = head # first = 1->2->3
second = prev # second = 5->4
first = head
second = prev

while second:
# 1회전: first=1, second=5
temp1 = first.next # temp1 = 2
temp2 = second.next # temp2 = 4

first.next = second # 1->5
second.next = temp1 # 5->2
# 현재 상태: 1->5->2->3, 남은 second = 4

first = temp1 # first = 2
second = temp2 # second = 4

# 2회전: first=2, second=4
temp1 = first.next # temp1 = 3
temp2 = second.next # temp2 = None

first.next = second # 2->4
second.next = temp1 # 4->3
# 현재 상태: 1->5->2->4->3

first = temp1 # first = 3
second = temp2 # second = None (종료)

# 최종 결과: 1->5->2->4->3
temp1 = first.next
temp2 = second.next

first.next = second
second.next = temp1

first = temp1
second = temp2
3 changes: 2 additions & 1 deletion reverse-linked-list/KwonNayeon.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,8 @@ def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
prev = None
curr = head

while curr is not None:
# 마지막 노드도 처리해야 함
while curr:

temp = curr.next
curr.next = prev
Expand Down