我试图编写一个方法来获取元素并删除它们之间的所有元素,如果两个元素中的一个不存在,则不会删除任何元素,所以我写了一个方法,但它没有&# 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;
}
答案 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;
然后,您可以删除node1
和node2
之间的元素。