LEETCODE

#19. Remove Nth Node From End of List

로그앤 2023. 10. 13. 17:14

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)
        left = dummy # left starts at dummy that points to head
        right = head # right starts at head
        while n > 0 and right: # expand right until n distance from left
            n -= 1
            right = right.next
        # when right is n distance from left check if right is at end
        while right: # at this point we are n units from left --> traverse till last right node
            left = left.next
            right = right.next
        left.next = left.next.next # last right node found. delete the n'th node from end now
        return dummy.next

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