Posted on by Kalkicode

# Insert linked list node at nth last position in python

Python program for Insert linked list node at nth last position. Here problem description and explanation.

``````#  Python 3 program for
#  Insert linked list node at nth last position

def __init__(self, data) :
self.data = data
self.next = None

def __init__(self) :

#  insert node at end position
def insert(self, value) :
#  Create a new node
else :
#  Find the last node
while (temp.next != None) :
#  Visit to next node
temp = temp.next

temp.next = node

def display(self) :
return

while (temp != None) :
print(temp.data ,end = " → ")
#  Visit to next node
temp = temp.next

print("NULL")

#  Add node at specific position from the end of linked list
def endPosition(self, position, value) :
elif (position <= 0) :
print("Invalid position")
else :
location = None
while (temp != None) :
position -= 1
if (position <= 0) :
if (location == None) :
else :
location = location.next

#  visit to next node
temp = temp.next

if (position <= 1) :
if (location == None) :
#  Add node at first place
else :
#  Add node at intermediate position
node.next = location.next
location.next = node

else :

def main() :
sll.insert(5)
sll.insert(4)
sll.insert(3)
sll.insert(2)
sll.insert(1)
sll.display()
position = 2
data = 10
sll.endPosition(position, data)
print(" Add", data ," at last", position ,"-nd position")
sll.display()

if __name__ == "__main__": main()``````

Output

``````5 → 4 → 3 → 2 → 1 → NULL
Add 10  at last 2 -nd position
5 → 4 → 3 → 2 → 10 → 1 → NULL``````

## Comment

Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

Categories
Relative Post