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