[LEETCODE] 206: Reverse Linked List(Python)

박나현·2024년 4월 29일

Reverse Linked List - LeetCode

문제 설명

단방향 연결 리스트가 주어질 때, 해당 리스트를 뒤집어 반환하는 문제이다.

나의 풀이

# 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]:
        if head==None:
            return None
        nxt = head.next
        prv = None
        head.next = prv
        prv = head
        
        while nxt != None:
            head = nxt
            nxt = nxt.next
            head.next = prv
            prv = head
        return head

자세한 설명은 이 글에 작성했다.

시간복잡도

순회하는 과정에서 O(n)이 걸린다.

profile
의견을 가지고 학습하기, 질문하기, 궁금했던 주제에 대해 학습하는 것을 미루지 않기

0개의 댓글