Suppose we have a linked list. We have to remove the Nth node from the end of the list, then return its head. So if the list is like [1, 2, 3, 4, 5, 6] and n = 3, then the returned list will be [1, 2, 3, 5, 6].
To solve this, we will follow these steps −
Let us see the following implementation to get a better understanding −
class ListNode: def __init__(self, data, next = None): self.val = data self.next = next def make_list(elements): head = ListNode(elements) for element in elements[1:]: ptr = head while ptr.next: ptr = ptr.next ptr.next = ListNode(element) return head def print_list(head): ptr = head print('[', end = "") while ptr: print(ptr.val, end = ", ") ptr = ptr.next print(']') class Solution(object): def removeNthFromEnd(self, head, n): if not head.next: return None front=head back = head counter = 0 flag = False while counter<=n: if(not front): flag = True break front = front.next counter+=1 while front: front = front.next back = back.next if not flag: temp = back.next back.next = temp.next temp.next = None else: head = head.next return head head = make_list([1,2,3,4,5,6]) ob1 = Solution() print_list(ob1.removeNthFromEnd(head, 3))