[Leetcode 19] Remove nth Node From End of List

이재윤·2025년 2월 11일
0

https://leetcode.com/problems/remove-nth-node-from-end-of-list/

1) 코드

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:
        
        dummy = head
        curr = ListNode(0)
        curr.next = head 
        res = curr 

        for _ in range(n):
            dummy = dummy.next

        while dummy:
            curr = curr.next
            dummy = dummy.next

        curr.next = curr.next.next

        return res.next

2) 해설

  • dummy 노드를 통해 n칸을 먼저 이동시켜 놓은 다음에
    curr 노드와 dummy 노드를 같이 이동시킨다
    -> 그렇게 하면 curr 노드가 제거해야 하는 노드 바로 앞에 위치하게 되므로,
    curr.next = curr.next.next를 통해서 해당 노드를 제거해준다

0개의 댓글