代码之家  ›  专栏  ›  技术社区  ›  Jacob Nelson

在双链表中添加节点[关闭]

  •  0
  • Jacob Nelson  · 技术社区  · 16 年前

    我正在编写一些代码,如果我需要将节点添加到双链接列表中。这是我目前掌握的代码:

    Node tempNext = cursor.getNext();
    temp = new Node(item, null, cursor, tempNext);
    tempNext.setPrev(temp);
    

    在哪里? cursor 在新添加的节点应该到达的位置之前的节点。

    如何设置其他节点以正确维护双链接列表的状态?

    3 回复  |  直到 13 年前
        1
  •  6
  •   rodrigoap    16 年前

    编写有意义的变量名总是有帮助的,不要使用像temp*这样的名称:

    protected void insertNodeAfter(Node currentNode, Node newNode) {
        Node displacedNode = currentNode.getNext();
        currentNode.setNext(newNode);
        newNode.setNext(displacedNode)
        displacedNode.setPrev(newNode);
        newNode.setPrev(currentNode);
    }
    
        2
  •  2
  •   Jacob Mattison    16 年前

    cursor.setNext(temp);
    

    你有什么特别的问题吗?

        3
  •  0
  •   Dave Clemmer manu    13 年前
    public void addItemBefore( int info )
    {
        previousItem = new ListItem( previousItem, info, this );
    }