# 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

## 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):
for element in elements[1:]:
while ptr.next:
ptr = ptr.next
ptr.next = ListNode(element)
print('[', end = "")
while ptr:
print(ptr.val, end = ", ")
ptr = ptr.next
print(']')
class Solution(object):
return None
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:
print_list(ob1.removeNthFromEnd(head, 3))
[1,2,3,4,5,6]
3
[1,2,3,5,6]