Skip to content

Instantly share code, notes, and snippets.

@jatinsharrma
Created May 3, 2020 20:32
Show Gist options
  • Save jatinsharrma/ee39fb1315393edf421add40a831b6be to your computer and use it in GitHub Desktop.
Save jatinsharrma/ee39fb1315393edf421add40a831b6be to your computer and use it in GitHub Desktop.
Delete n-th element from the last : Singly linked list
# ////////////////////////////////////////////////////
# --------Deleting n-th element from last-------------
# ////////////////////////////////////////////////////
'''
Logic :
Suppose we have a linked list 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7 -> 8 -> 9 -> 0
And we were ask to delete 6th element from last, which is '5'
We traverse the linked list till 6th element of list, which is '6'
If 6th element is None then we will delete 1st element, which is 1
But in our case it is not none.
So we take a new pointer (k) which will point to root
our previous pointer (j) is at elemment '7'
1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7 -> 8 -> 9 -> 0
k j
Now we will move both pointer 1 ahead and
continue till j reaches last element, which is '0'
So,
1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7 -> 8 -> 9 -> 0
k j
1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7 -> 8 -> 9 -> 0
k j
1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7 -> 8 -> 9 -> 0
k j
Automatically k will be at (n + 1) element from the last.
So we simply delete the nth element from the last
Uncomment code to see changes in linked list
'''
# Node class
class Node:
def __init__(self, value):
self.data = value
self.next = None
def setNext(self,next):
self.next = next
def getNext(self):
return self.next
def getData(self):
return self.data
def setData(self, data):
self.data = data
# Making a liked list
node = Node(1) # root node
last = node # last node
item = [2,3,4,5,6,7,8,9,0] # items to be inserted
for i in item:
last.setNext(Node(i))
last = last.getNext()
# print('-----------Items Before deleting-----------------')
# new_node = node
# while new_node is not None:
# print(new_node.getData())
# new_node = new_node.getNext()
# print('-------------------------------------------------')
# delete method
def deleteFromLast(node,k):
node_1 = node
count = 1
while count <= k and node_1 is not None:
node_1 = node_1.getNext()
count += 1
value = None
if count < k+1:
return "Index out of bound"
if node_1 is None:
value = node.getData()
node.setData(node.getNext().getData())
node.setNext(node.getNext().getNext())
return value
node_2 = node
while node_1.getNext() is not None:
node_1 = node_1.getNext()
node_2 = node_2.getNext()
value = node_2.getNext().getData()
node_2.setNext(node_2.getNext().getNext())
return value
# testing --
print("Result : " , deleteFromLast(node,6))
# print('-----------Items After deleting-----------------')
# new_node = node
# while new_node is not None:
# print(new_node.getData())
# new_node = new_node.getNext()
# print('-------------------------------------------------')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment