미소를뿌리는감자의 코딩
[leetcode 2024/02/13] 206. Reverse Linked List 본문
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
'코딩 테스트 > leetcode' 카테고리의 다른 글
[leetcode 2024/02/13] 328. Odd Even Linked List (0) | 2024.02.13 |
---|---|
[leetcode 2024/02/13] 21. Merge Two Sorted Lists (0) | 2024.02.13 |
[leetcode 2024/02/08] 215. Kth Largest Element in an Array (0) | 2024.02.08 |
[leetcode 2024/02/08] 1337. The K Weakest Rows in a Matrix (0) | 2024.02.08 |
[leetcode 2024/02/08] 1464. Maximum Product of Two Elements in an Array (0) | 2024.02.08 |