我目前正在实现的python中有一个链表。但是,删除第一个节点的情况不适用于我。
删除列表中其他任何位置的节点都可以。
我搜索了youtube教程和其他在线帖子,但似乎有与我完全相同的代码行。
我还尝试过将打印语句放在各行之前 -self.head = HeadVal.nextval -HeadVal =无
从输出中看,它似乎确实将根节点传递到了列表的第二个元素上,并清除了原始的第一项,但是当我再次打印列表时,原始的第一个节点尚未被删除。它是否就像新的列表结构尚未提交到内存那样?
类节点: def init(self,dataval): self.dataval =数据值 self.nextval =无
LinkedList类: def init(self): self.headval =无
def listprint(self):
printval = self.headval
while printval is not None:
print (printval.dataval)
printval = printval.nextval
def insertAtBegining(self):
nodeToPutAtStart = input("Enter Node To Put At The Start: ")
startNode = Node()
startNode.init(nodeToPutAtStart)
startNode.nextval = self.headval
self.headval = startNode
print(nodeToPutAtStart, " Has Been Added To The Start Of The Linked List")
def insertAtEnd(self):
nodeToPutOnEnd = input("Enter Node To Put On The End: ")
endNode = Node()
endNode.init(nodeToPutOnEnd)
if self.headval is None:
self.headval = endNode
return
laste = self.headval
while(laste.nextval):
laste = laste.nextval
laste.nextval=endNode
print(nodeToPutOnEnd, " Has Been Added To The End Of The Linked List")
def removeNode(self):
nodeToRemove = input("Enter Node To Remove: ")
HeadVal = self.headval
if (HeadVal is not None):
if (HeadVal.dataval == nodeToRemove):
self.head = HeadVal.nextval
HeadVal = None
return
else:
print("B")
while (HeadVal is not None):
if HeadVal.dataval == nodeToRemove:
break
prev = HeadVal
HeadVal = HeadVal.nextval
prev.nextval = HeadVal.nextval
HeadVal = None
else:
print("Nothing To Delete")
def MainMenu():
print("1. Create A Linked List")
print("2. Delete A Linked List")
print("3. Check If A Linked List Is Empty")
print("4. Print Out The Values In The List")
print("5. Find A Node In A Linked List")
print("6. Insert A Node In A Linked List")
print("7. Delete A Node In A Linked List")
print("99. Exit")
anotherOption = True
while anotherOption == True:
print("")
selection=int(input("Main Menu --- Enter Choice: "))
if selection==1:
myList = LinkedList()
myList.init()
print("Linked List Created")
elif selection==6:
print("")
print("A. Insert A Node Into The Front Of The Linked List")
print("B. Insert A Node Into The End Of The Linked List")
print("")
entrySelection=input("Enter Insert Node Choice: ")
if entrySelection in ["A", "a"]:
myList.insertAtBegining()
elif entrySelection in ["B", "b"]:
myList.insertAtEnd()
else:
print("")
print("Enter A Valid Selection For Inserting Node")
elif selection==4:
myList.listprint()
elif selection==7:
myList.removeNode()
elif selection==99:
anotherOption = False
print("")
print("Exiting Main Menu")
else:
print("")
print("Enter A Valid Selection On Main Menu")
MainMenu()