Skip to content
Merged
Changes from all 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
27 changes: 27 additions & 0 deletions reverse-linked-list/jylee2033.py
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🏷️ 알고리즘 패턴 분석

  • 패턴: Reverse Linked List
  • 설명: 이 코드는 연결 리스트의 방향을 뒤집는 문제로, 기존 링크를 역순으로 재구성하는 과정을 통해 해결합니다. 일반적인 패턴인 'Reverse Linked List'에 속하며, 포인터 조작을 통해 리스트를 뒤집습니다.

Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
# Handle empty list
# if head is None:
# return head

prev = None
cur = head # Start from the head node

# Traverse until the last node
while cur is not None:
nxt = cur.next # Store next node
cur.next = prev # Reverse the link
prev = cur # Move prev forward
cur = nxt # Move cur forward

# Handle the last node
# cur.next = prev
return prev

# Time Complexity: O(n)
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

수고 많으셨습니다!
시/공간 복잡도도 잘 정리해주셔서 좋네요 😊

while cur is not None: 패턴을 쓰면

  • 빈 리스트 처리용 if head is None 분기 없이도 동작하고
  • 마지막 노드를 따로 처리하지 않아도 돼서

조금 더 읽기 쉬운 코드가 될 것 같습니다~!

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

오 감사합니다! 알려주신 대로 다시 풀어보니까 예외 처리도 줄고 훨씬 깔끔해지네요. 팁 감사합니다 😊

# Space Complexity: O(1)
Loading