简体   繁体   中英

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

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM