如何删除我在链表中​​选择的两个元素之间的所有元素

时间:2015-02-28 11:54:00

标签: java linked-list

我试图编写一个方法来获取元素并删除它们之间的所有元素,如果两个元素中的一个不存在,则不会删除任何元素,所以我写了一个方法,但它没有&# 39;工作它陷入循环,见代码:

注意: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;

}

2 个答案:

答案 0 :(得分:1)

从头开始你会更好。你根本不需要嵌套循环,更不用说任务的五个级别,基本上是线性的。

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

  • 首先,您需要确定第一个元素是否存在。使用单个while循环执行此操作。如果到达目的地,请退出。
  • 将对第一个元素的引用存储在单独的变量first中,并继续查找第二个元素
  • 再次使用单独的while循环。如果在找到第二个元素之前到达列表的末尾,请退出。
  • 如果找到第二个元素,请将其指定给first.next

就是这样,你完成了。您可以使用两个连续的while循环,甚至使用一个while循环和一些boolean变量来完成此操作。不需要嵌套。

答案 1 :(得分:0)

制作了一个代码,实际上几乎与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之间的元素。