Reputation: 81
I was reading this article about implementation of simple LinkedList in Java and adapted it with almost no changes to my small project. Everything is working well but remove method.
The deal is that I have to remove corresponding element. I mean (that is my remove method):
private Link head;
public void remove(Object obj) {
if (task == null)
System.out.println("no");
else {
Link linkCurr = head;
if (head != null) {
for (int i = 0; i < size; ++i) {
if (obj.equals(linkCurr.getData())){
linkCurr.setNext(linkCurr.getNext().getNext());
size--;
break;
}
linkCurr = linkCurr.getNext();
}
}
}
}
That is the class that operates the logic of nodes and links.
private class Link
{
Link next;
Object data;
public Link(Object data) {
next = null;
this.data = data;
}
public Task getData() {
return data;
}
public Link getNext() {
return next;
}
public void setNext(Link next)
{
this.next = next;
}
}
So, the problem is the following - when I delete first obj in the list (by setting it as the parameter of remove) - it disappears, but if I try to remove second or any else, the next one after what I wanted is getting deleted.
I would appreciate any help, thanks in advance. In case more info is needed, full code of my LinkedList here!.
Upvotes: 1
Views: 740
Reputation: 3764
The issue appears to be in this section of code:
Link linkCurr = head;
if (head != null) {
for (int i = 0; i < size; ++i) {
if (obj.equals(linkCurr.getData())){
linkCurr.setNext(linkCurr.getNext().getNext());
size--;
break;
}
linkCurr = linkCurr.getNext();
}
}
What this is doing is searching through the list for a node that matches the inputted node. It then is setting that node's next link to the node 2 down the line, removing the adjacent node.
You are probably wanting to keep an index of the previous node, and performing the setnext on that, something like:
Link linkCurr = head;
Link previous = null;
if (head != null) {
for (int i = 0; i < size; ++i)
{
if (obj.equals(linkCurr.getData()))
{
if (previous == null)
{
head = linkCurr.getNext(); // sets 2nd position to head of list
size--;
break;
}
previous.setNext(linkCurr.getNext()); // removes the node
size--;
break;
}
previous = linkCurr;
linkCurr = linkCurr.getNext();
}
}
Upvotes: 4