I have two lists ItemsList , ilist . If the nodes of ilist contain the same values as the nodes of ItemsList i have to delete them from ItemsList however i get that my list is empty each time i use the remove function from the code below :
public void remove(ItemsList ilist) {
if (empty()) {
System.out.println("The list is empty.");
} else {
this.bubblesort();
ilist.bubblesort();
ItemNode a = this.first;
ItemNode b = ilist.first;
for(a=first;a!=null;a=a.next) {
for(b=first;b!=null;b=b.next) {
if(a.item==b.item) {
this.deleteNode(a.item);
}
}
}
}
}
private void deleteNode(int data) {
ItemNode prev = null;
for(ItemNode trace = first; trace != null; trace = trace.next) {
if(trace.item == data) {
if (prev == null) {
first = trace.next;
} else {
prev.next = trace.next;
}
}
else {
prev = trace;
}
}
}
Lets say i have ItemsList : [0,1,2,3,4] and ilist : [0,1] which means 0 ,1 will be deleted from ItemsList but when i display the ItemsList it says that it's empty . I cannot use arrays , arraylists or other java libraries for the specific problem . Thank you for your time .
解决方案
What I would do:
public void remove(ItemsList iList) {
if (iList.isEmpty()) {
System.out.println("The list is empty.");
} else {
ItemNode prev = null;
ItemNode a = this.first;
while (a != null) {
for (ItemNode b = iList.first; b != null; b = b.next) {
if (a.item == b.item) prev.next = a.next;
}
a = a.next;
}
}
}