Recursive code to remove Nth node from the end of a singly linked list

It’s been a while since I have written something here. A lot of work is going on and haven’t got much time tbh. So, here’s a piece of recursive code to delete the N-th node from the end of a singly linked list.
The problem statement (from leetcode) is as follows:

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]

Constraints:

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

Well, an array of solutions are possible for this problem, but I have tried the recursive one which passed all the test cases. Given below is the solution class, the driver class for the same can be found here link.

# 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: ListNode, n: int) -> ListNode:
        curr_node = head
        curr_pos = 0
        
        def mark_node(curr, n):            
            if not curr.next:
                curr_pos = 2
                if n == 1:
                    return (curr_pos, False)
                return (curr_pos, True)

            curr_pos, flag =  mark_node(curr.next, n)
            
            if curr_pos == n:
                return curr_pos + 1, False
            
            if not flag:
                curr.next = curr.next.next
                
            return curr_pos+1, True
        
        _, flag = mark_node(curr_node, n)
        if not flag:
            head = head.next
            
        return head

Well let me know if this can be optimised further.

Thanks

Leave a comment

Blog at WordPress.com.

Up ↑

Design a site like this with WordPress.com
Get started