|
| 1 | +// Node class |
| 2 | +class Node { |
| 3 | + constructor(data) { |
| 4 | + this.data = data; |
| 5 | + this.next = null; |
| 6 | + } |
| 7 | +} |
| 8 | + |
| 9 | +// Circular Linked List class |
| 10 | +class CircularLinkedList { |
| 11 | + constructor() { |
| 12 | + this.head = null; |
| 13 | + } |
| 14 | + |
| 15 | + // Insert node at the end |
| 16 | + insert(data) { |
| 17 | + const newNode = new Node(data); |
| 18 | + if (!this.head) { |
| 19 | + this.head = newNode; |
| 20 | + newNode.next = this.head; // point to itself |
| 21 | + return; |
| 22 | + } |
| 23 | + |
| 24 | + let temp = this.head; |
| 25 | + while (temp.next !== this.head) { |
| 26 | + temp = temp.next; |
| 27 | + } |
| 28 | + temp.next = newNode; |
| 29 | + newNode.next = this.head; // complete the circle |
| 30 | + } |
| 31 | + |
| 32 | + // Delete a node by value |
| 33 | + delete(data) { |
| 34 | + if (!this.head) return; |
| 35 | + |
| 36 | + let current = this.head; |
| 37 | + let prev = null; |
| 38 | + |
| 39 | + // If head node itself needs to be deleted |
| 40 | + if (current.data === data) { |
| 41 | + // If only one node |
| 42 | + if (current.next === this.head) { |
| 43 | + this.head = null; |
| 44 | + return; |
| 45 | + } |
| 46 | + |
| 47 | + // Find the last node to fix circular link |
| 48 | + let last = this.head; |
| 49 | + while (last.next !== this.head) { |
| 50 | + last = last.next; |
| 51 | + } |
| 52 | + |
| 53 | + last.next = this.head.next; |
| 54 | + this.head = this.head.next; |
| 55 | + return; |
| 56 | + } |
| 57 | + |
| 58 | + // Search for the node to delete |
| 59 | + do { |
| 60 | + prev = current; |
| 61 | + current = current.next; |
| 62 | + if (current.data === data) { |
| 63 | + prev.next = current.next; |
| 64 | + return; |
| 65 | + } |
| 66 | + } while (current !== this.head); |
| 67 | + } |
| 68 | + |
| 69 | + // Display all elements |
| 70 | + display() { |
| 71 | + if (!this.head) { |
| 72 | + console.log("List is empty"); |
| 73 | + return; |
| 74 | + } |
| 75 | + |
| 76 | + let result = ""; |
| 77 | + let temp = this.head; |
| 78 | + do { |
| 79 | + result += temp.data + " -> "; |
| 80 | + temp = temp.next; |
| 81 | + } while (temp !== this.head); |
| 82 | + |
| 83 | + console.log(result + "(back to head)"); |
| 84 | + } |
| 85 | +} |
| 86 | + |
| 87 | +// Example usage |
| 88 | +const cll = new CircularLinkedList(); |
| 89 | + |
| 90 | +cll.insert(10); |
| 91 | +cll.insert(20); |
| 92 | +cll.insert(30); |
| 93 | +cll.insert(40); |
| 94 | + |
| 95 | +console.log("Circular Linked List:"); |
| 96 | +cll.display(); |
| 97 | + |
| 98 | +console.log("Deleting 20..."); |
| 99 | +cll.delete(20); |
| 100 | +cll.display(); |
0 commit comments