Reputation: 472
I am having trouble with my remove method for circular Linked List. It only executes the if statement. What am i doing wrong? How do I fix this issue? In a circular linked List you only need to keep track of the first element pointing to the last
public void remove()
{
Node currNode = first;
Node prevNode = null;
if(first != null)
{
if(currNode.getNext() == first)
{
first = null;
}
}
else
{
prevNode = currNode;
currNode = currNode.getNext();
}
}
class Node
{
private int data;
private Node next;
public Node(int data, Node next) {
this.data = data;
this.next = next;
}
public int getData() {
return data;
}
public Node getNext() {
return next;
}
public void setNext(Node next) {
this.next = next;
}
}
Upvotes: 2
Views: 1543
Reputation: 41
I will be making certain assumptions, since I can't post a comment
-You access the circular linked list using the first Node, that means if first is not null your circular linked list is not empty
-secondly you call the remove() function only when the linked list is non empty, so from my first assumption you cannot reach the else block.
Your remove() logic is NOT clear.
If you invoke remove() when first!=null or linked list in non-empty you are checking if the second node is same is first and then deleting the reference to first(first=null) means you lose the linked list without assigning the second node to be the new first(node). To me it looks like you deleted the entire linked list not just the first element.
Now If you invoke remove() function on an empty linked list i.e first=null
currNode= first //currNode = null
so the else block will look like this
prevNode=null;
currNode=null.getNext() //Null pointer Exception!!
Last I checked in circular linked list , the next of last node should point to the first node and not the first pointing to the last.
PS-If any of my assumptions are wrong please comment instead of downvoting :)
Upvotes: 0
Reputation: 60104
Node currNode = first;
Node prevNode = null;
is local variable, so after function remove(), they deleted, and you didn't store this value. Every times when you call remove() you have some value in currNode and prevNode. So you should use this variable as class variable:
...
Node currNode = first;
Node prevNode = null;
public void remove()
{
if(first != null)
{
if(currNode.getNext() == first)
{
first = null;
}
}
else
{
prevNode = currNode;
currNode = currNode.getNext();
}
}
Or you should use currNode.setNext(...) instead of currNode = ...
Upvotes: 2