首页 > 解决方案 > 在现有节点之间插入一个节点

问题描述

我有一个插入方法,我需要帮助在两个节点之间插入一个新节点

这是代码:

@Override
public void insert(int index, E data) throws ListOverflowException {
    Node<E> curr = startOfNode;
    int ctr = 0;

    // adds the data in the specified index in the linked list
    for (curr = startOfNode; curr !=null; curr = curr.getNext()) {
        if (ctr == index) {
            Node<E> newNode = new Node<>(data);
            curr.setNext(newNode);
            newNode.setNext(curr.getNext());
            break;
        }
        ctr++;
    }

    if (size == maxSize) {
        throw new ListOverflowException("Error! Can't add any more nodes");
    }
}

这是初始列表:

Item 1 :4
Item 2 :5
Item 3 :6
Item 4 :8
Item 5 :9
Item 6 :null

这是我得到的结果。如您所见,拥有 8 号和 9 号的节点丢失了。如何修改循环以获得所需的结果:

Item 1 :4
Item 2 :5
Item 3 :6
Item 4 :7
Item 5 :null

标签: javainsertnodes

解决方案


您的第一种方法是有缺陷的,因为您从要插入的索引中省略了所有节点,因此丢失了所有链接。

在您的第二种方法中,您有正确的想法,但是您会得到一个无限循环,因为您curr.getNext() 插入新节点之后会这样做。解决方法是在插入新节点之前获取节点,临时保存,添加新节点,并将临时保存的节点设置为插入节点的下一个。

它应该看起来像这样:

Node<E> newNode = new Node<>(data);
Node<E> tempNode = curr.getNext(); // retrieve the initially following node
curr.setNext(newNode);             // insert the new node
newNode.setNext(tempNode);         // reconstruct the link

推荐阅读