본문 바로가기

알고리즘

[파이썬 알고리즘 인터뷰] 역순 연결 리스트

728x90
 

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

재귀 구조로 뒤집기

def reverseList(self, head) -> ListNode:
    def reverse(node, prev):
        if not node:
            return prev
        next, node.next = node.next, prev
        return reverse(next, node)

    return reverse(head)

반복 구조로 뒤집기

def reverseList(self, head) -> ListNode:
    node, prev = head, None

    while node:
        next, node.next = node.next, prev
        prev, node = node, next
    
    return prev

 

반응형