https://leetcode.com/problems/reverse-linked-list/
Reverse Linked List - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
풀이 과정
링크드 리스트를 뒤집는 문제이다.
링크드 리스트를 뒤집는 방법은 반복문으로 뒤집기, 재귀를 활용해서 뒤집기 2가지 방법이 가능하고 문제에서도 후속조치로 2가지 방법으로 모두 구현할 수 있냐고 묻고 있다.
재귀, 반복 2가지 방법으로 구현하였다.
소스 코드
재귀
class Solution:
def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
def reverse(node, prev=None):
if not node:
return prev
next, node.next = node.next, prev
return reverse(next, node)
return reverse(head)
반복
class Solution:
def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
rev = None
answer = []
while head:
rev, rev.next, head = head, rev, head.next
return rev
'알고리즘 문제 풀이 > 리트코드' 카테고리의 다른 글
LeetCode - 24. Swap Nodes in Pairs [Python] (0) | 2022.07.27 |
---|---|
LeetCode - 2. Add Two Numbers [Python] (0) | 2022.07.27 |
LeetCode - 234. Palindrome Linked List [Python] (0) | 2022.07.23 |
LeetCode - 121. Best Time to Buy and Sell Stock [Python] (0) | 2022.07.22 |
LeetCode - 238. Product of Array Except Self [Python] (0) | 2022.07.22 |