我这里的目标是给函数"省略"一个整数,如果该整数在某个节点的"info"槽中,则该节点将被删除。我知道我必须要做什么,只是执行起来有点困难。下面是我的ListNode内部类:
private int howmany;
private ListNode c;
private class ListNode {
private int info;
private ListNode link;
public ListNode() {
info = 0;
link = null;
}
public ListNode(int i, ListNode pointer) {
info = i;
link = pointer;
}
}
这里是我尝试的省略方法:
public void omit(int i){
ListNode pointer;
pointer = c;
if (pointer.info == i){
pointer=pointer.link;
}
ListNode prev = pointer;
ListNode curr = pointer.link;
while (curr != null) {
if (curr.info == i){
prev.link = curr.link;
}else{
prev = prev.link;
curr = curr.link;
}
}
这个省略方法不起作用。我在我的客户中尝试过,我试图忽略的数字留在列表中。谁能告诉我我哪里做错了?
假设您找到一个节点,其中curr.info == i
。在这种情况下,不修改导致无限循环的curr
。此外,在列表的开头,您最多跳过一个节点,但可以有任意数量的节点需要提交。
最好的方法是遍历列表,并将未提交的节点与最后一个未提交的节点连接起来:
public void omit(int i){
// remove elements from the start of the list
while (c != null && c.info == i) {
c = c.next;
}
ListNode lastKept = c;
ListNode current = c;
while (current != null) {
current = current.next;
// find next node to be kept
while (current != null && current.info == i) {
current = current.next;
}
lastKept.next = current;
lastKept = current;
}
}