문제
Given the head of a singly linked list, reverse the list, and return the reversed list
단일 연결 리스트의 헤드 노드가 주어졌을때 리스트를 뒤집어 리턴하셈
https://leetcode.com/problems/reverse-linked-list/
예시
풀이
class Solution:
def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
# 빈 노드, 시작점 설정
prev, curr = None, head
# 리스트가 끝날때 까지
while curr:
nextNode = curr.next # 다음 노드 미리 저장
curr.next = prev # 다음 노드를 기존 노드로 방향 설정
prev = curr # 현재 노드 수정
curr = nextNode # 다음 노드로 이동
return prev
반응형
'알고리즘 & 자료구조 > Leetcode' 카테고리의 다른 글
[Leetcode 146] - LRU Cache w/ Python (0) | 2024.04.07 |
---|---|
[Leetcode 287] - Find the Duplicate Number w/ Python (1) | 2024.04.07 |
[Leetcode 141] - Linked List Cycle w/ Python (0) | 2024.04.07 |
[Leetcode 2] - Add Two Numbers w/ Python (0) | 2024.04.07 |
[Leetcode 138] - Copy List with Random Pointer w/ Python (1) | 2024.04.06 |