【发布时间】:2020-06-28 02:59:27
【问题描述】:
我在 python 中创建了一个非常标准的链表,其中包含 Node 类和 LinkedList 类。我还为 LinkedList 添加了如下方法:
- add(newNode):将元素添加到链表中
- addBefore(valueToFind, newNode):在具有指定值的元素之前添加一个新节点。
- printClean:打印链表
我正在尝试使用 addBefore 方法执行插入,但是如果插入不在头部,它将不起作用。我不知道为什么。
class Node:
def __init__(self, dataval =None):
self.dataval = dataval
self.nextval = None
class LinkedList:
def __init__(self, headval =None):
self.headval = headval
def add(self, newNode):
# The linked list is empty
if(self.headval is None):
self.headval = newNode
else:
# Add to the end of the linked list
currentNode = self.headval
while currentNode is not None:
# Found the last element
if(currentNode.nextval is None):
currentNode.nextval = newNode
break
else:
currentNode = currentNode.nextval
def addBefore(self, valueToFind, newNode):
currentNode = self.headval
previousNode = None
while currentNode is not None:
# We found the element we will insert before
if (currentNode.dataval == valueToFind):
# Set our new node's next value to the current element
newNode.nextval = currentNode
# If we are inserting at the head position
if (previousNode is None):
self.headval = newNode
else:
# Change previous node's next to our new node
previousNode.nexval = newNode
return 0
# Update loop variables
previousNode = currentNode
currentNode = currentNode.nextval
return -1
def printClean(self):
currentNode = self.headval
while currentNode is not None:
print(currentNode.dataval, end='')
if(currentNode.nextval != None):
print("->", end='')
currentNode = currentNode.nextval
else:
return
testLinkedList = LinkedList()
testLinkedList.add(Node("Monday"))
testLinkedList.add(Node("Wednesday"))
testLinkedList.addBefore("Wednesday", Node("Tuesday"))
testLinkedList.printClean()
星期一->星期三
【问题讨论】:
-
嗨,你这里有一个错字:``` # 将前一个节点的旁边更改为我们的新节点 previousNode.nexval = newNode
, change topreviousNode.nextval = newNode```会做。 -
"is None" 有时会导致奇怪的意外问题,通常最好对所有条件使用简单的 Python 真实性。例如:stackoverflow.com/questions/6497166/…
标签: python data-structures linked-list