Remove Nth Node From End of List in Python

PythonServer Side ProgrammingProgramming

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 −

  • If there is no node after head, then return None
  • front := head, back := head, counter := 0 and fount := false
  • while counter <= n
    • if front is not present, then set flag as true, and come out from the loop
    • front := next of front, and increase counter by 1
  • while front is present
    • front := next of front
    • back := next of back
  • if flag is false, then
    • temp := next of back
    • next of back := next of temp
    • next of temp := None
  • otherwise head := next of head
  • Return head

Example(Python)

Let us see the following implementation to get a better understanding −

 Live Demo

class ListNode:
   def __init__(self, data, next = None):
      self.val = data
      self.next = next
def make_list(elements):
   head = ListNode(elements[0])
   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))

Input

[1,2,3,4,5,6]
3

Output

[1,2,3,5,6]
raja
Published on 30-Jan-2020 14:58:21
Advertisements