Reputation: 133
How to remove an element from the linked list?
Is it correct way:
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;
}
}
The problem is when I am printing all elements, getAllElements() is NOT giving correct answer,is there any problem in remove() method or getAllElements
public void getAllElements() {
Node<E> aNode = currentNode;
while(aNode != null) {
aNode.printNode();
aNode = aNode.previous;
}
}
Upvotes: 0
Views: 637
Reputation: 133
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;
}
I have found the solution for that Issue, thanks everyone for yours kind support.
Upvotes: 0
Reputation: 4701
Try this:
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;
}
}
Upvotes: 1
Reputation: 66
It seems like your remove method does not really remove anything, you should update the pointers in your method so that nothing points toward the element you want to remove, and then garbage collector will the remove the element that nothing points to. Some pseudocode to illustrate what I mean:
public remove(Element element){
for (Element e : myLinkedList){
if (e.equals(element)){
if (next != 0)
previousPtr = nextPtr;
else
previousPtr = null;
}
}
}
Note this is not correct Java code, just pseudocode to give you an idea, I save some fun for you!! :)
Upvotes: 1
Reputation: 4872
The line
if(search.previous.toString().equals(element.toString())
calls to string on the node and not on the element.
Upvotes: 1
Reputation: 2412
Don't your elements have some kind of identifier? Then you can do it much simpler, like here: remove an object
Upvotes: 0