python - 如何修复这个链表算法

标签 python python-3.x linked-list

我想在链接列表中的特定元素(第二个 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/

相关文章:

python-docx中心表内容

python - PyBrain 强化学习输入缓冲区不正确

python - 如何使用 Python 将二维数组中的列分配给某个重复范围?

python-3.x - urlopen 返回有效链接的重定向错误

python - 最近 pip 安装 Python 模块后文件版本错误

C链表 "redefinition of structure"

python - 无法在 Docker 中运行 BaseHTTPServer

c++ - 升序排序 - 链表

c - 尝试实现 Dijkstra,但存在毫无意义的段错误

python - Django CentOS 7 - 无法导入名称 Col