From 6cf94be4215696ca076973de8291b138b4f139e5 Mon Sep 17 00:00:00 2001 From: VishwajeetK Date: Tue, 3 Dec 2024 10:54:08 +0530 Subject: [PATCH] feat: Implement circular linked list and Add insert, delete and display methods --- .../dsa/linkedlist/CircularLinkedList.java | 73 +++++++++++++++++++ .../practice/dsa/linkedlist/CircularMain.java | 21 ++++++ 2 files changed, 94 insertions(+) create mode 100644 JavaDsaWithTest/src/main/java/org/practice/dsa/linkedlist/CircularLinkedList.java create mode 100644 JavaDsaWithTest/src/main/java/org/practice/dsa/linkedlist/CircularMain.java diff --git a/JavaDsaWithTest/src/main/java/org/practice/dsa/linkedlist/CircularLinkedList.java b/JavaDsaWithTest/src/main/java/org/practice/dsa/linkedlist/CircularLinkedList.java new file mode 100644 index 0000000..8ff3847 --- /dev/null +++ b/JavaDsaWithTest/src/main/java/org/practice/dsa/linkedlist/CircularLinkedList.java @@ -0,0 +1,73 @@ +package org.practice.dsa.linkedlist; + +public class CircularLinkedList { + + private Node head; + private Node tail; + + public CircularLinkedList() { + this.head = null; + this.tail = null; + } + + public void insert(int val) { + Node node = new Node(val); + if (head == null) { + head = node; + tail = node; + return; + } + tail.next = node; + node.next = head; + tail = node; + } + + public void display() { + Node node = head; + if (head != null) { + do { + System.out.print(node.val + "->"); + if (node.next != null) { + node = node.next; + } + } while (node != head); + } + System.out.println("HEAD"); + } + + public void delete(int val) { + Node node = head; + if (node == null) { + return; + } + + if (head == tail) { + head = null; + tail = null; + return; + } + + if (node.val == val) { + head = head.next; + tail.next = head; + } + + do { + Node n = node.next; + if (n.val == val) { + node.next = n.next; + break; + } + node = node.next; + } while (node != head); + } + + private class Node { + int val; + Node next; + + public Node(int val) { + this.val = val; + } + } +} diff --git a/JavaDsaWithTest/src/main/java/org/practice/dsa/linkedlist/CircularMain.java b/JavaDsaWithTest/src/main/java/org/practice/dsa/linkedlist/CircularMain.java new file mode 100644 index 0000000..77e7c0d --- /dev/null +++ b/JavaDsaWithTest/src/main/java/org/practice/dsa/linkedlist/CircularMain.java @@ -0,0 +1,21 @@ +package org.practice.dsa.linkedlist; + +public class CircularMain { + public static void main(String[] args) { + CircularLinkedList cll = new CircularLinkedList(); + + cll.insert(10); + cll.insert(11); + cll.insert(12); + cll.insert(13); + cll.insert(14); + cll.insert(15); + + cll.display(); + + cll.delete(12); + cll.delete(13); + + cll.display(); + } +}