Search code examples
javacircular-list

deleting value from Circular Linked List


There is a problem with my code, after I delete the node, the same node appears as previous node in the next node. Trying to remove node 4.

Pervious: Node: 5; Node: 15; NextNode: 16 | Pervious: Node: 15; Node: 16; NextNode: 29 | Pervious: Node: 16; Node: 29; NextNode: 4 | Pervious: Node: 29; Node: 4; NextNode: 5 | Pervious: Node: 4; Node: 5; NextNode: 15 |

After removing

Pervious: Node: 5; Node: 15; NextNode: 16 | Pervious: Node: 15; Node: 16; NextNode: 29 | Pervious: Node: 16; Node: 29; NextNode: 5 | Pervious: Node: 4; Node: 5; NextNode: 15

public Node deleteValue(int i) {
    Node node = start;
    do {
        if (node.next.getData() == i) {
            Node n = node.next;
            node.next = n.next;

            size--;

            if (n == start) { 
                start = node;

            }
            return n;
        }][1]

        node = node.next;
    } while(node != start);
    return null;
}

Solution

  • When you delete you item, you are missing a simple line of code. You must set your previous element's next element, and the next-next element's previous element. You are actually missing the second part. This is what the code should look like :

    Node current = start;
    do{
      if(current.getData() == i){
        // set the previous's next element
        current.previous.next = current.next;
        // set the next element's previous element
        current.next.previous = current.previous;
        this.size--;
        return current;
      }
      current = current.next;
    }while(node != start);
    return null;