我必须编写这些方法的代码。这是一项家庭作业,不能改变方法的参数,或者写其他方法。 contains()和isEmpty()正常工作。 removeFirst()和removerLast()也可以很好地工作。为什么LinkedList的removeAll()和removeFirstOccurrence()删除节点?
removeFirstOccurence()不会删除指定元素的第一个成员。 而removeAll()不会取消所有指定的元素。
/**
* Removes the first occurrence of the specified element in this list (when
* traversing the list from head to tail). *
* @param value element to be removed from this list, if present
* @return {@code true} if the list contained the specified element
*/
public boolean removeFirstOccurrence(int value) {
if(!contains(value))
return false;
else{
boolean result = false;
Node current = head;
while ((current != null) && !result) {
if (current.value == value){
current=current.next;
size--;
return true;
}
current = current.next;
}
return result;
}
}
/**
* Removes all occurrences of the specified element from this list.
* @param value the element to remove
* @return {@code false} if nothing changed, otherwise {@code true}
*/
public boolean removeAll(int value) {
if(isEmpty())
return false;
else{
boolean result = false;
Node current = head;
while ((current.next != null) && !result) {
if (current.value == value){
current=current.next;
size--;
result=true;
}
current= current.next;
}
return result;
}
}
这里MyLinkedList类的第一部分:
public class MyLinkedList {
private class Node {
private int value;
private Node next;
private Node(int value) {
this.value = value;
this.next = null;
}
@Override
public String toString() {
...
}
}
private Node head;
private int size;
//和方法...
你在哪里更改当前节点的下一个值? –