From 101233a69479add310fb808b324717655dacda04 Mon Sep 17 00:00:00 2001 From: Vishant Rathi <129350236+vishantrathi@users.noreply.github.com> Date: Tue, 15 Oct 2024 11:25:38 +0530 Subject: [PATCH] Create Circular Doubly Linked List Similar to a doubly linked list but with the last node pointing back to the first node --- .../lists/Circular Doubly Linked List | 55 +++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 src/main/java/com/thealgorithms/datastructures/lists/Circular Doubly Linked List diff --git a/src/main/java/com/thealgorithms/datastructures/lists/Circular Doubly Linked List b/src/main/java/com/thealgorithms/datastructures/lists/Circular Doubly Linked List new file mode 100644 index 000000000000..227b47cbeabc --- /dev/null +++ b/src/main/java/com/thealgorithms/datastructures/lists/Circular Doubly Linked List @@ -0,0 +1,55 @@ +class CircularDoublyLinkedList { + private Node head; + + // Constructor + public CircularDoublyLinkedList() { + head = null; + } + + // Insert a node at the end + public void insertEnd(int data) { + Node newNode = new Node(data); + if (head == null) { + head = newNode; + head.next = head; + head.prev = head; + } else { + Node tail = head.prev; + + tail.next = newNode; + newNode.prev = tail; + newNode.next = head; + head.prev = newNode; + } + } + + // Display the list + public void display() { + if (head == null) { + System.out.println("List is empty."); + return; + } + + Node current = head; + do { + System.out.print(current.data + " "); + current = current.next; + } while (current != head); + System.out.println(); + } + + // Delete a node by value + public void delete(int value) { + if (head == null) return; + + Node current = head; + + do { + if (current.data == value) { + if (current == head && current.next == head) { + head = null; // List is now empty + } else { + current.prev.next = current.next; + current.next.prev = current.prev; + if (current == head) { + head = current.next; // Move head