如何在链表中的另一个之前插入和元素 [英] How to insert and element before another in a linked list

查看:104
本文介绍了如何在链表中的另一个之前插入和元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

这就是我要的.我在将newElement插入预期元素之前遇到麻烦.似乎无法弄清楚它的语法.我已经花了一段时间了,我能得到的最好的办法是将它插入到当前元素之后

This is what I have for this. I'm having troubles to insert the newElement before intended element. Can't seem to figure out the syntax for it. I've been tinkering with it for a while and the best I could get was for it to insert after the element like it currently does

任何帮助将不胜感激

推荐答案

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

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;
        }
    }
}

这篇关于如何在链表中的另一个之前插入和元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆