【发布时间】:2017-11-08 21:39:50
【问题描述】:
我正在尝试删除循环链表中所有出现的给定键,例如:
1 -> 0 -> 1 -> 0
key number = 1 删除所有出现的数字 1 并最终得到:
0 -> 0
但我的代码得到的是:
0 -> 1 -> 0 -> 1
它将头部移动到列表的末尾而不是删除它。
我发现的另一个问题是,如果有 2 个或多个具有相同值的数字彼此相邻,它将总是留下一个,例如:
0 -> 1 -> 1 -> 0
我得到了这个结果
0 -> 1 -> 0
代码
public void remove(int num) {
if (isEmpty()) {
System.out.println("Empty List");
} else {
Node currentLink = head;
Node previousLink = head;
boolean run = true;
while (run) {
if (currentLink.data == num) {
currentLink.size--;
if (currentLink == head) { //Delete head
head = head.next; // Deletes head but then it appears on the end of the list
} else
previousLink.next = currentLink.next; // Deletes all occurrences of a given key but always leaves one if they are next to each other
}
previousLink = currentLink;
currentLink = currentLink.next;
if (currentLink == head) run = false;
}
}
}
【问题讨论】:
标签: java data-structures linked-list