如何从链表中删除元素?
方法是否正确:
public E remove(E element) {
Node search = currentNode;
boolean nonStop = true;
while(((search.previous) != null) && (nonStop)) {
if(search.previous.toString().equals(element.toString())) {
System.out.println("Item found !!!");
search.previous = search.previous.previous;
nonStop = false;
} else {
search = search.previous;
}
}
currentNode = search;
return null;
}
public class Node<E> {
public E data;
public Node<E> previous;
public Node(E data) {
this.data = data;
}
public void printNode() {
System.out.println("Node details: "+data);
}
@Override
public String toString() {
// TODO Auto-generated method stub
return (String)data;
}
}
问题是当我打印所有元素时,getAllElements() 没有给出正确答案,remove() 方法或 getAllElements 是否有问题
public void getAllElements() {
Node<E> aNode = currentNode;
while(aNode != null) {
aNode.printNode();
aNode = aNode.previous;
}
}