My ninth submission in my 2026 LeetCode series. This problem is 19. Remove Nth Node From End of List.
The problem is,
Given the head of a linked list, remove the nth node from the end of the list and return its head.
When I first attempted to solve this problem, I did not pay close attention to the phrase, end of list. I thought the goal - which is easier - was to delete the nth node in the LinkedList.
The actual problem is to delete the nth node from the end of the list. This requires that we know the number of nodes in the list. Once that is known, we can then keep track of the count of the current node we are on and how far we are from the end of the LinkedList.
Here is my solution:
# 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]:
if head.next is None and n == 1:
head = head.next
return head
temp = head
head_copy = head
len_list = 0
# Traverse List till end to get count of items
while head_copy is not None:
len_list += 1
head_copy = head_copy.next
# If nth node to delete is head node, set head to next node
if n == len_list:
head = head.next
return head
# Delete nth item from list while traversing
i = 0
while head.next is not None:
if len_list - i -1 == n:
head.next = head.next.next
break
else:
head = head.next
i += 1
return temp
What do you think about this? Is there a better way to do this?
Top comments (0)