简体   繁体   中英

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

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) {

    }

}

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.

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> .

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

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

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