From 9e742e7f8c18fdebe7d896f7b44f62eedfd5203a Mon Sep 17 00:00:00 2001 From: Toihir Halim <66559721+toihirhalim@users.noreply.github.com> Date: Sun, 4 Apr 2021 21:28:46 +0200 Subject: [PATCH] Add circular linked list java (#134) --- linked-lists/README.md | 1 + linked-lists/java/circular.java | 69 +++++++++++++++++++++++++++++++++ 2 files changed, 70 insertions(+) create mode 100644 linked-lists/java/circular.java diff --git a/linked-lists/README.md b/linked-lists/README.md index e057737d..0eb09c14 100644 --- a/linked-lists/README.md +++ b/linked-lists/README.md @@ -13,6 +13,7 @@ 1. [Singly Linked List](java/singly.java) 2. [Doubly Linked List](java/doubly.java) +2. [Circular Linked List](java/circular.java) ### JavaScript diff --git a/linked-lists/java/circular.java b/linked-lists/java/circular.java new file mode 100644 index 00000000..3d6067dc --- /dev/null +++ b/linked-lists/java/circular.java @@ -0,0 +1,69 @@ +class CircularLinkedList{ + class Node { + int value; + Node next; + + public Node(int value) { + this.value = value; + } + } + + private Node head = null; + private Node tail = null; + + public void addNode(int value) { + Node newNode = new Node(value); + + if (head == null) { + head = newNode; + } else { + tail.next = newNode; + } + + tail = newNode; + tail.next = head; + } + public void printNodes() { + Node current = head; + if(head == null) { + System.out.println("List is empty"); + return; + } + System.out.println("The circular linked list is: "); + System.out.print("[ "); + do{ + System.out.print(current.value + " "); + current = current.next; + //go to next until we get back to the head + }while(current != head); + System.out.println("]"); + } +} + +public class circular { + public static void main(String [] args){ + CircularLinkedList cll = new CircularLinkedList(); + + cll.addNode(10); + cll.addNode(12); + cll.addNode(2); + cll.addNode(1); + cll.addNode(8); + cll.addNode(42); + cll.addNode(17); + + cll.printNodes(); + + //this will print : + /* + The circular linked list is: + [ 10 12 2 1 8 42 17 ] + */ + } +} + +/* + to run the file: + javac circular.java + java circular +*/ \ No newline at end of file