Ok so the idea for me is to be moving to each node(user in this case) in a circular list and asking if they would like to log off,they will give a random yes or no answer,until everyone has logged off. this seems to be the case most of the time i run the program but sometimes users are logging back on which shouldn't happen,I will post the delete method and the display method i am using.
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
}
}
解决方案
I think your problem is in this line
else if(!rand)
Add a boolean that checks if the user has been deleted
else if(!rand && !userExists)