【问题标题】:How to fix this algorithm of linked list如何修复这个链表算法
【发布时间】:2019-12-18 22:59:29
【问题描述】:

我想在链表上的特定元素(第二个 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 python-3.x linked-list


    【解决方案1】:

    通过新节点的下一个插入,而不是通过当前节点的下一个并返回头部。在这里,我在特定节点之后粘贴到插入节点.. [在 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;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-04-11
      • 2017-09-25
      • 1970-01-01
      • 2020-05-03
      • 2020-08-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多