我想在链接列表中的特定元素(第二个 Joey)之后添加一个元素(steve)。
当前列表:Ash->joey->Alex->Cook->Joey->bing。
所需输出:Ash->joey->Alex->Cook->Joey->steve->bing
这是我的代码:
def insert_at_same(self , newNode, data_to_check):
currentNode = self.head
temp = 0
while currentNode.next is not None:
if (temp == 1 and currentNode.data == data_to_check):
tempNode = currentNode.next
currentNode.next = newNode
newNode.next = tempNode
return
elif currentNode.data == data_to_check:
temp = temp + 1
else:
currentNode = currentNode.next
但我的输出仍然是:Ash->joey->steve->Alex->Cook->Joey->bing。
最佳答案
通过新节点的下一个插入,而不是通过当前节点的下一个插入并返回头。在这里,我粘贴以在特定节点后插入节点..[在Python中更改它]
插入后/下一个
SLL temp = head;
SLL current = null;
while(temp.next != null) {
current = temp;
/* if the node found, after where you need to insert */
if(current.name.equals(nodeName)) {
SLL newName = new SLL(name);
/* newnode will point to second of current node */
newName.next = current.next;
/* initialize the new_node, to current node */
current.next = newName;
return head;
}
temp = temp.next;
}
/* if the node found at the last position of list */
if(temp.name.equals(nodeName)) {
temp.next = new SLL(name);
}
return head;
插入前/前
/* if the node found at first of list */
if(head != null && head.name.equals(nodeName)) {
SLL newName = new SLL(name);
newName.next = head;
head = newName;
return head;
}
SLL temp = head;
SLL current = null;
/* traverse the list, until the node is found */
while(temp.next != null && !temp.name.equals(nodeName)) {
current = temp;
temp = temp.next;
}
SLL newName = new SLL(name);
newName.next = current.next;
current.next = newName;
return head;
关于python - 如何修复这个链表算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57459914/