- 문제 링크: https://leetcode.com/problems/reverse-linked-list/
- 난이도: Easy
기본적인 싱글 링크드리스트 문제. 리스트 방향을 거꾸로 만드는 문제다.
iterative/recursive 두가지 방법을 모두 써볼 수 있다.
(1) Iterative Solution
class Solution:
def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
prev, curr = None, head
while curr:
temp = curr.next
curr.next = prev
prev = curr
curr = temp
return prev
(2) Recursive Solution
class Solution:
def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
if not head or not head.next:
return head
new_head = self.reverseList(head.next)
head.next.next = head
head.next = None
return new_head
반응형
'Online Judge > LeetCode' 카테고리의 다른 글
[LeetCode][Python] 19. Remove Nth Node From End of List (0) | 2024.09.13 |
---|---|
[LeetCode][Python] 21. Merge Two Sorted Lists (0) | 2024.09.11 |
[LeetCode][Python] 567. Permutation in String (0) | 2024.09.10 |
[LeetCode][Python] 424. Longest Repeating Character Replacement (0) | 2024.09.09 |
[LeetCode][Python] 121. Best Time to Buy and Sell Stock (0) | 2024.09.08 |