코딩 테스트 및 알고리즘/Grind 75 (Blind 75 Leetcode Questions)

LinkedList : Remove Nth Node From End of List

띠리링구 2024. 1. 17. 08:37

https://leetcode.com/problems/remove-nth-node-from-end-of-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

 

포인터를 두 개 둔다

두 개의 포인터를 n+1칸 간격으로 유지하면서 전진시키고

뒤쪽 포인터가 끝까지 가면

앞쪽 포인터를 이용해 뒤에서 n번째의 노드를 제거하면 된다.

 

# 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]:
        p = head
        
        for i in range(n):
            p = p.next

        if not p:
            return head.next
        
        p = p.next
        nprev = head

        while p:
            p = p.next
            nprev = nprev.next

        nprev.next = nprev.next.next

        return head