In: Computer Science
The programming language is Python
Instructions:
Create a function that will delete a node in a Linked List based on position number. On below example, if you want to delete position #2, it will remove the Banana (arrangement of nodes below is Apple, Banana, Cherry, Grapes, Orange).
myLinkedList = LinkedList()
myLinkedList.append("Banana")
myLinkedList.append("Cherry")
myLinkedList.append("Grapes")
myLinkedList.append("Orange")
myLinkedList.prepend("Apple")
myLinkedList.deleteByPositionNum(2)
node = myLinkedList.head
while node:
print(node.value, " ")
node = node.next_node
You may start with the function head:
def deleteByPositionNum(self, positionNum):
class Node:
def __init__(self, value):
self.value = value
self.next_node= None
class LinkedList:
def __init__(self):
self.head = None
def append(self, new_data):
new_node = Node(new_data)
if self.head is None:
self.head = new_node
return
last = self.head
while (last.next_node):
last = last.next_node
last.next_node = new_node
def deleteByPositionNum(self, positionNum):
i=1
temp=self.head
prev=self.head
while(i<=positionNum ):
if (i==1):
i=i+1
continue
prev = temp
temp = temp.next_node
i=i+1
if(temp==self.head) :
self.head = temp.next_node
temp = None
return
if(temp == None):
return
prev.next_node = temp.next_node
temp = None
if __name__=='__main__':
myLinkedList = LinkedList()
myLinkedList.append("Apple")
myLinkedList.append("Banana")
myLinkedList.append("Cherry")
myLinkedList.append("Grapes")
myLinkedList.append("Orange")
myLinkedList.append("Apple")
myLinkedList.deleteByPositionNum(2)
node = myLinkedList.head
while node:
print(node.value)
node= node.next_node
OUTPUT :