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
LinkedList를 뒤집는 문제입니다.
재귀함수를 이용해 리스트를 타고 끝을 찾은 뒤 끝에서부터 재귀함수를 빠져나오면서 연결 방향을 거꾸로 뒤집었습니다.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
if(not head or not head.next):
return head
rest = self.reverseList(head.next)
head.next.next = head
head.next = None
return rest
input = ListNode(1,ListNode(2, ListNode(3,ListNode(4, ListNode(5,None)))))
# input = None
answer = Solution().reverseList(input)
while(answer):
print(answer.val)
answer = answer.next
'🔍 알고리즘 > Leetcode' 카테고리의 다른 글
[Python] Leetcode 213. House Robber II (Medium) (0) | 2022.07.23 |
---|---|
[Python] Leetcode 198. House Robber (Medium) (0) | 2022.07.23 |
[Python] Leetcode 21. Merge Two Sorted Lists (Easy) (0) | 2022.07.23 |
[Python] Leetcode 746. Min Cost Climbing Stairs (Easy) (0) | 2022.07.22 |
[Python] Leetcode 70. Climbing Stairs (Easy) (0) | 2022.07.22 |