如何修复此链表算法

时间:2019-08-12 10:57:51

标签: python python-3.x linked-list

我想在特定元素(第二乔伊)之后的链接列表上添加一个元素(史蒂夫)。

当前列表: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。

1 个答案:

答案 0 :(得分:0)

插入到newnode的下一个而不是currentNode的下一个,然后返回head。在这里,我粘贴要在特定节点之后插入节点.. [在Python中更改]

插入后/下一个

ID  Project Amount  Start Date  New Sum
1234    203 29.65   5/29/18     Blank
1234    203 2       6/24/18     31.65
1234    203 345.34  7/12/18     Blank
1234    201 100     7/16/18     100
1234    203 200     7/16/18     545.34
2345    251 3       4/11/17     Blank
2345    251 4       4/16/17     7
2345    203 95.12   8/13/18     95.12
2345    203 10      4/12/19     10
3456    251 50      3/23/18     Blank
3456    251 100     3/23/18     150
3456    251 43.75   6/5/18      43.75

在/ PREV之前插入

    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;