Ad Code

Responsive Advertisement

Ticker

6/recent/ticker-posts

Circular linked list DSA

 class Node {

  constructor(data) {

    this.data = data;

    this.next = null;

  }

}

 

class CircularLinkedList {

  constructor() {

    this.head = null;

    this.tail = null;

  }

 

  insert(data) {

    const node = new Node(data);

    if (this.head === null) {

      this.head = node;

      this.tail = node;

      node.next = node;

    } else {

      node.next = this.head;

      this.tail.next = node;

      this.tail = node;

    }

  }

 

  delete(data) {

    if (this.head === null) {

      return;

    }

    let current = this.head;

    let previous = null;

    do {

      if (current.data === data) {

        if (current === this.head) {

          this.head = current.next;

          this.tail.next = this.head;

        } else if (current === this.tail) {

          previous.next = this.head;

          this.tail = previous;

        } else {

          previous.next = current.next;

        }

        return;

      }

      previous = current;

      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 CircularLinkedList();

list.insert(1);

list.insert(2);

list.insert(3);

list.insert(4);

list.traverse((data) => console.log(data));

list.delete(2);

list.traverse((data) => console.log(data));

 

Output:

 

Elements are:

1

2

3

4

deleted element  : 2

1

3

4

Post a Comment

0 Comments

Ad Code

Responsive Advertisement