본문 바로가기

LEETCODE

#19. Remove Nth Node From End of List [Sliding window]

Given the head of a linked list, remove the nth node from the end of the list and return its head.

Example 1:
Input: head = [1,2,3,4,5], n = 2
Output: [1,2,3,5]


Example 2:
Input: head = [1], n = 1
Output: []


Example 3:
Input: head = [1,2], n = 1
Output: [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 = ListNode(0,head) # insert dummy as first null node
        left = dummy # left starts at dummy
        right = head # expand right until n distance from left
        while n > 0 and right: # expand until right is at end of list
            right = right.next
            n -= 1
        while right: # when right is n distance from left check if right is at end
            left = left.next
            right = right.next
        # delete when right is at end
        left.next = left.next.next
        return dummy.next

https://leetcode.com/problems/remove-nth-node-from-end-of-list/?envType=featured-list&envId=top-interview-questions?envType=featured-list&envId=top-interview-questions