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;
}
}
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 = ...