Deletion in a Circular Linked List
Wed Mar 20 2024
deleteFromLinkedList:
A sophisticated function tailored for the precise removal of a specified value from a circular linked list. This operation begins with a thorough search to locate the target node, employing a do-while loop to traverse the circular structure efficiently. Upon finding the node, the function adeptly adjusts pointers to excise the node from the list, ensuring the circular nature of the list remains intact. Special considerations are made for edge cases, such as deleting the head node or a node in a singleton list, demonstrating the method's attention to maintaining the list's integrity and continuity.
1class Node {
2  constructor(val) {
3    this.data = val;
4    this.next = null;
5  }
6}
7
8class CircularLinkedList {
9  constructor() {
10    this.head = null;
11  }
12  addLast(val) {
13    const newNode = new Node(val);
14    if (!this.head) {
15      this.head = newNode;
16      this.head.next = this.head;
17      return;
18    }
19    let currentHead = this.head;
20    let current = this.head;
21    while (current.next !== currentHead) {
22      current = current.next;
23    }
24    newNode.next = currentHead;
25    current.next = newNode;
26  }
27  size() {
28    let count = 0;
29    let currentHead = this.head;
30    let current = this.head;
31    while (count === 0 || current !== currentHead) {
32      count++;
33      console.log(current.data);
34      current = current.next;
35    }
36    return count;
37  }
38  print() {
39    let count = 0;
40
41    let current = this.head;
42    while (count === this.size()) {
43      count++;
44      console.log(current.data);
45      current = current.next;
46    }
47  }
48  deleteFromLinkedList(val) {
49    if (!this.head) return;
50
51    let current = this.head;
52    let prev = null;
53    let found = false;
54
55    do {
56      if (current.data === val) {
57        found = true;
58        break;
59      }
60      prev = current;
61      current = current.next;
62    } while (current !== this.head);
63
64    if (!found) return;
65
66    if (this.head === this.head.next && this.head.data === val) {
67      this.head = null;
68      return;
69    }
70
71    if (current === this.head) {
72      prev = this.head;
73      while (prev.next !== this.head) {
74        prev = prev.next;
75      }
76      this.head = this.head.next;
77      prev.next = this.head;
78    } else {
79      prev.next = current.next;
80    }
81  }
82}
83
84let linkedList = new CircularLinkedList();
85linkedList.addLast('1');
86linkedList.addLast('2');
87linkedList.addLast('3');
88linkedList.addLast('4');
89linkedList.print();
90console.log('<====>');
91// console.log(linkedList.head)
92
93linkedList.deleteFromLinkedList('1');
94linkedList.print();
95