如何删除链表中我select的两个元素之间的所有元素

How to removes all the elements between the two elements that I select in linked list

我正在尝试编写一个方法,该方法接受元素并删除它们之间的所有元素,如果两个元素之一不存在,则不会删除任何元素,所以我写了一个方法,但它不起作用它陷入了循环,请参阅代码:

注意:1- 我无法调用任何方法。 2- 我不能使用任何辅助数据结构。

public void removeBetween(T e1, T e2) {

    if (head == null) {
        return;
    }

    Node<T> tmp1 = current;

    current = head;

    while (current != null) {

        if (current.data.equals(e1)) {
            current = head;
            while (current != null) {

                if (current.data.equals(e2)) {

                    current = head;
                    while (current != null) {

                        if (current.data.equals(e1)) {

                            while (current.data != e2) {

                                if (current == head) {

                                    head = head.next;
                                } else {

                                    Node<T> tmp = head;

                                    while (tmp.next != current) {

                                        tmp = tmp.next;
                                        tmp.next = current.next;
                                    }

                                    if (current.next == null)
                                        current = head;

                                    else
                                        current = current.next;
                                }

                                current = current.next;

                            }
                        }
                        current = current.next;
                    }
                }
                current = current.next;
            }

        }

        current = current.next;

    }

    current = tmp1;

}

你最好从头开始。您根本不需要嵌套循环,更不用说五层嵌套了,本质上是线性的。

解决手头的任务有一个简单的计划:

  • 首先,您需要找出第一个元素是否存在。用一个 while 循环来完成。如果你到达终点,退出。
  • 将对第一个元素的引用存储在一个单独的变量中first,并继续寻找第二个元素
  • 再次使用单独的 while 循环。如果在找到第二个元素之前到达列表末尾,则退出。
  • 如果找到第二个元素,将其分配给 first.next

就是这样,你已经完成了。您可以使用两个连续的 while 循环,甚至可以使用一个 while 循环和几个 boolean 变量。无需嵌套。

编写了一个代码,实际上几乎完成了 dasblinkenlight 已经说明的内容。

Node<T> current = head; // set the current to head
do {
    current = current.next; // go to next
    if (current == head) { // if it's head, we have reached the end -> return
        return;
    }
} while (!current.data.equals(e1)); // if current.data is wrong, continue loop
Node<T> node1 = current; // match found
do { // do the same again, starting from current, to find the second node
    current = current.next;
    if (current == head) {
        return;
    }
} while (!current.data.equals(e2));
Node<T> node2 = current;

那么就可以去掉node1node2之间的元素了。