python - 插入链表 Python
问题描述
我在 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()
星期一->星期三
解决方案
希望这可以帮助
def addBefore(self, valueToFind, newNode):
currentNode = self.headval # point to headval
previousNode = None
while currentNode.data != valueToFind: # while currentNode.data is not equal to valueToFind, move currentNode to next node and keep track of previous node i.e. previousNode
previousNode = currentNode # keep tack of previous node
currentNode = currentNode.nextval # move to next node
previousNode.nextval = newNode # previous node will point to new node
previousNode = previousNode.nextval # move previous node to newly inserted node
previousNode.nextval = currentNode # previous node ka next will to currentNode
推荐阅读
- c# - 尝试从 aspx 元标记中的代码访问公共变量后,当前上下文中不存在名称“ ”
- javascript - 用悬念测试 Vue3 异步设置组件的正确方法是什么?
- json - 如何从串联列表中找出元素的原始列表?
- regex - 在 sed 单行中用空格替换/删除 2 个字符
- javascript - 在 JS 内存中,对象是否存储为块?
- python - 在 3D 空间中以最小最近邻距离和最大密度随机采样给定点
- algorithm - 使用间隙成本函数找到 2 个字符串之间的最佳对齐
- php - PHP选择图像路径并显示是否主图像
- python - 偏移平行于给定线的线/向量
- php - 包括来自另一个文件的函数(不起作用= wordpress)