且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在链表中的另一个之前插入和元素

更新时间:2023-11-09 23:48:28

在单个链表的情况下,您将需要两个临时节点:

In case of a single linked list, you will need two temporary nodes:

  • MyNode<E> current将代表单个链接列表中的当前节点.
  • MyNode<E> prev,它将表示单个链接列表中当前节点之前的节点.
  • MyNode<E> current that will represent the current node in the single linked list.
  • MyNode<E> prev that will represent a node before the current node in the single linked list.

然后,您必须在这些节点之间添加新节点.如果没有prev节点,则将current节点设置为新节点的下一个节点时,current之前的所有节点都将丢失.

Then, you have to add the new node between these nodes. If you don't have the prev node, then when setting the current node as the next node of the new node, then all the nodes before current will be lost.

这是您的代码的样子:

public void insertElementBefore(E element, E newElement) {
    MyNode<E> current = head;
    //check here
    MyNode<E> prev = null;
    if (head != null) {
        while (current != null) {
            if (current.data.equals(element)) {
                MyNode<E> n = new MyNode<E>(newElement);
                n.next = current;
                //check here
                if (prev != null) {
                    prev.next = n;
                }
                return;
            }
            //check here
            prev = current;
            current = current.next;
        }
    }
}