Java循环链表,删除不一致
我的想法是移动到循环列表中的每个节点(本例中的用户),询问他们是否想要注销,他们会随机给出是或否的答案,直到每个人都注销。在我运行程序的大多数时候似乎都是这样,但有时用户会重新登录,这是不应该发生的,我会发布我正在使用的delete方法和display方法Java循环链表,删除不一致,java,adt,nodes,circular-list,Java,Adt,Nodes,Circular List,我的想法是移动到循环列表中的每个节点(本例中的用户),询问他们是否想要注销,他们会随机给出是或否的答案,直到每个人都注销。在我运行程序的大多数时候似乎都是这样,但有时用户会重新登录,这是不应该发生的,我会发布我正在使用的delete方法和display方法 public void displayLinkedList() { temp=first; int i = 1; do { boolean rand=randomBoolean(
public void displayLinkedList() {
temp=first;
int i = 1;
do {
boolean rand=randomBoolean();
if(rand) {
System.out.println("USER : "+temp.data+" Logged off ");
temp.isloggedOut=true;
Node placeholder = temp.nextNode; //save value of temp.next before we delete temp
delete(temp);
Node.numOfUsers--;
temp = placeholder; //reassign "temp" to the appropriate next value.
} else if(!temp.isloggedOut) {
System.out.println("USER : "+temp.data+" Logged on ");
temp=temp.nextNode;
}
} while(Node.numOfUsers!=0);
}
public void delete(Node n) {
if(Node.numOfUsers == 0 || n == null) return; // 0 nodes or null parameter.
Node temp = first;
if(temp.nextNode == null) { //only one node
temp = null; //simply delete it
} else {
while(temp.nextNode != n) {
temp = temp.nextNode;
if(temp == first) { //if we circle the entire list and don't find n, it doesn't exist.
return;
}
}
temp.nextNode = n.nextNode; // perform the switch, deleting n
}
}
我认为你的问题在这方面
else if(!rand)
添加一个布尔值,用于检查用户是否已被删除
else if(!rand && !userExists)
在上述代码中,从该列表中删除
temp
变量后,将引用该变量。这可能会导致一些问题。调整为下面的代码
do {
boolean rand=randomBoolean();
if(rand) {
System.out.println("USER : " + temp.data + " Logged off ");
Node placeholder = temp.next; //save value of temp.next before we delete temp
delete(temp);
Node.numOfUsers--;
temp = placeholder; //reassign "temp" to the appropriate next value.
} else {
System.out.println("USER : " + temp.data + " Logged on ");
temp = temp.nextNode;
}
} while(Node.numOfUsers != 0);
还有,有趣的事实。如果(!rand)出现在您最初发布的代码中,则无需执行
其他操作。通过将第一个case设置为if(rand)
唯一正确的情况是rand==true
对吗?因此,唯一的另一个逻辑情况是rand==false
,因此,如果语句检查这个,那么甚至不需要第二个,因为我们知道它不可能是其他任何东西。要创建userExists方法,我必须去命名我的所有节点?@MickO'Gorman问得好。您可能只需要在创建对象时使用该对象的哈希代码。看到刚才做的,我以为它是工作了几次,但最后一次我尝试一个用户重新登录,我只是尝试了4个用户添加的原因,你得到的不一致是因为兰德是随机的。有时它会偶然打印“登录”,因为您没有强制执行其他检查。考虑将布尔变量添加到节点类“ISLogGoDeOUT”中,然后可以在登录时说“否则(.TEMP.ISLoggDeOUT)”,并得到可靠的结果。在从链接列表中删除时,请确保将值切换为false。好的,现在尝试一下,我认为一旦我从列表中删除了一个节点,我就不必担心它会通过登录而不是注销的过程返回。这只是为了良好的设计。你验证过你的删除方法100%有效吗?好的,我已经验证过了,但是这次我让人注销了两次,我很确定我之前检查过删除方法