Instagram
youtube
Facebook
Twitter

Remove Nth Node From End Leetcode Solution

In this tutorial, we will solve a leetcode problem,  remove Nth node from the end in python.

Task:

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

Example1:

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

 

Example2:

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


Example 3:

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

Constraints:

  • The number of nodes in the list is sz.
  • 1 <= sz <= 30
  • 0 <= Node.val <= 100
  • 1 <= n <= sz

 

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 == None:
            return None
        count=0
        cur = head
        while cur:
            count+=1
            cur =cur.next
        if count == 2 and n==1:
            head.next =None
            return head
        elif count==2 and n==2:
            head = head.next
            return head
        cur1 = head
        if count-n == 0:
            return head.next
        for i in range(count-n):
            if i == (count-n-1):
                cur1.next = cur1.next.next
            cur1 = cur1.next
        return head