如何从链表中删除元素?
这是正确的方式:
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;
}
}
答案 0 :(得分:1)
该行
if(search.previous.toString().equals(element.toString())
调用节点上的字符串而不是元素。
答案 1 :(得分:1)
看起来你的 remove方法并没有真正删除任何东西,你应该更新你方法中的指针,这样就没有任何东西指向你想要删除的元素,然后垃圾收集器将删除没有任何意义的元素。一些伪代码来说明我的意思:
public remove(Element element){
for (Element e : myLinkedList){
if (e.equals(element)){
if (next != 0)
previousPtr = nextPtr;
else
previousPtr = null;
}
}
}
注意这是不是正确的Java代码,只是伪代码给你一个想法,我为你节省了一些乐趣! :)
答案 2 :(得分:1)
试试这个:
public void remove(E element)
{
Node n = head; // This is the head of the linked list-- It is the starting node of your linked list: For your case "currentNode"
Node tmp;
while(n!=null && !n.data.equals(element))
{
tmp = n;
n = n.previous;
}
if(n==null)
{
// Do your stuff
System.out.println("Element "+element+" not found.");
}
else
{
// Do your stuff
tmp.prev = n.prev;
n.prev = null;
System.out.println("Element "+element+" removed.");
}
}
// Suggestion: This method name should be "printList()"
public void getAllElements()
{
Node n = head; // In your case: "currentNode"
while(n!=null)
{
n.printNode();
n = n.previous;
}
}
答案 3 :(得分:0)
你的元素不具有某种标识符吗? 然后你可以更简单地做到这一点,比如:remove an object
答案 4 :(得分:0)
public E remove(E element) {
Node search = currentNode;
boolean nonStop = true;
while(((search.previous) != null) && (nonStop)) {
if(search.previous.data.equals(element)) {
System.out.println("Item found !!!");
search.previous = search.previous.previous;
nonStop = false;
}
search = search.previous;
}
return null;
}
我找到了该问题的解决方案,感谢大家的支持。