19. Remove Nth Node From End of List
  1. Remove Nth Node From End of List
class Solution:
    def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:
        if n==0:
            return head
        r = head
        nodes = []
        while r!= None:
            nodes.append(r)
            r = r.next
        # print(len(nodes))
        if n == len(nodes):
            return head.next
        
        delItemIndex = len(nodes)-n
        beforeindex = delItemIndex - 1
        afterIndex = delItemIndex + 1
        if beforeindex <0:
            if afterIndex > len(nodes):
                return head
            return head.next
        else:
            if afterIndex >= len(nodes):
                nodes[beforeindex].next = None
                return head
            
        nodes[beforeindex].next = nodes[afterIndex]
        return head
Comments (0)