class Node {
constructor(data) {
this.data = data;
this.prev = null;
this.next = null;
}
}
class
DoublyCircularLinkedList {
constructor() {
this.head = null;
}
insert(data) {
const node = new Node(data);
if (this.head === null) {
node.prev = node;
node.next = node;
this.head = node;
} else {
node.prev = this.head.prev;
node.next = this.head;
this.head.prev.next = node;
this.head.prev = node;
}
}
delete(data) {
console.log("Deleted Elements is
:" ,data);
if (this.head === null) {
return;
}
let current = this.head;
do {
if (current.data === data) {
if (current === this.head) {
this.head = current.next;
}
current.prev.next = current.next;
current.next.prev = current.prev;
return;
}
current = current.next;
} while (current !== this.head);
}
traverse(callback) {
if (this.head === null) {
return;
}
let current = this.head;
do {
callback(current.data);
current = current.next;
} while (current !== this.head);
}
}
// Example
usage:
const list =
new DoublyCircularLinkedList();
list.insert(1);
list.insert(2);
list.insert(3);
list.insert(4);
console.log("Elements
are:")
list.traverse((data)
=> console.log(data));
list.delete(2);
list.traverse((data)
=> console.log(data));
Output:
Elements are:
1
2
3
4
Deleted
Elements is : 2
1
3
4
0 Comments