코딩 테스트/leetcode
[leetcode 2024/02/13] 206. Reverse Linked List
미뿌감
2024. 2. 13. 13:48
728x90
https://leetcode.com/problems/reverse-linked-list/description/
LeetCode - The World's Leading Online Programming Learning Platform
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
1. 접근 방법
이번 문제는 노드의 방향을 반대로 하여, head를 출력하는 문제이다.
save, current, before을 이용해서 노드의 .next의 방향을 반대로 바꾸어 주었다.
이런식으로 노드의 방향을 바꾸어주었다. 이후,
save -> current
current -> save 로 저장되는 노드를 바꾸어주었다.
2. 코드
# 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]:
before = None
current = head
while current:
save = current.next
current.next = before
before = current
current = save
return before
728x90