How can you implement Delete and Search in a circular singly linked list?

451 views Asked by At

I am trying to implement a delete(Node x) method and a search(E key) method, but I don't understand how I can make a loop that traverses the list? I tried writing the delete method. Here is my code so far:

public class CircularSinglyLinkedList<E> {

    private Node<E> head;
    private Node<E> tail;

    private class Node<E> {
        public final E key;
        public Node<E> next;

        private Node(E key) {
            this.key = key;
        }
    }

    public void insert(Node<E> x) {
        x.next = head;
        tail.next = x;
        head = x;
    }

    public void delete(Node<E> x) {
        Node<E> y = head;
        while(y != x && y.next != head) {
            y = y.next;
        }
        if(y.next == x) {
            y.next = x.next;
            x.next = null;
        }
    }

    public E search(E key) {

    }

}
3

There are 3 answers

1
akhil_mittal On

You will need to traverse the circular list for deletion and search of a node. I hope the following code will be helpful:

private Node delete(Node x) {
    Node node = head;
    do {
        if (node.next.element == x.element) {
            Node n = node.next;
            node.next = n.next;
            if (n == head) { // removal of head
                head = node;
            }
            return n;
        }
        node = node.next();
    } while(node != head);
    return null;
}

It will search for node x and delete it. Though you have not posted the structure of your Node class but I still hope that you can make relevant changes.

The function will refuse to remove last element (when list contains only one element) as in circular linked list I assume last element has head for its next.

0
AudioBubble On

You need to implement equals and hashCode methods in the Node class.

while(!y.equals(x) && !y.next.equals(head)) {
    y = y.next;
}
0
hotkey On

I suppose, all you need is to transform your loop to do-while post-condition loop, like this:

Node<E> y = head;
do {
    if (y.next == x) {
        y.next = x.next;
        x.next = null;
        return;
    }
    y = y.next;
} while (y != head);

It would also be better to implement node search in your search method (making it return Node<E>).

By the way, delete method takes Node<E> as an argument, but it will be difficult to call it from outside, because caller cannot get reference to Node<E> from anywhere: head and tail are private, and search returns E, not Node<E>.