Skip to content

Commit

Permalink
feat: Implement circular linked list and Add insert, delete and displ…
Browse files Browse the repository at this point in the history
…ay methods
  • Loading branch information
VishwajeetVT committed Dec 3, 2024
1 parent 0edff80 commit 6cf94be
Show file tree
Hide file tree
Showing 2 changed files with 94 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -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;
}
}
}
Original file line number Diff line number Diff line change
@@ -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();
}
}

0 comments on commit 6cf94be

Please sign in to comment.