Skip to content

Instantly share code, notes, and snippets.

@prameshbajra
Created June 5, 2018 13:43
Show Gist options
  • Save prameshbajra/ea1a46eae00fc8ef5ff34b4306c89beb to your computer and use it in GitHub Desktop.
Save prameshbajra/ea1a46eae00fc8ef5ff34b4306c89beb to your computer and use it in GitHub Desktop.
By - Pramesh Bajracharya
package com.demo.advjava;
public class CircularLinkedList {
Node head;
class Node {
int data;
Node next;
public Node(int data) {
this.data = data;
}
}
public void addElementAtLast(int data) {
Node newNode = new Node(data);
if (head == null) {
newNode.next = newNode;
head = newNode;
System.out.println("Head: "+head.data+" NewNode: "+newNode.data);
} else {
Node current = head;
while (current.next != head) {
current = current.next;
}
current.next = newNode;
newNode.next = head;
}
}
public void addElement(int data)
{
Node temp = new Node(data);
if(head == null)
{
head = temp;
head.next = head;
}
else
{
Node current = head;
while(current.next != null )
{
if(current.next == head)
break;
current = current.next;
}
current.next = temp;
temp.next = head;
}
}
public void printAll() {
Node current = head;
while (current.next != head) {
System.out.println(current.data);
current = current.next;
}
System.out.println(current.data);
}
public static void main(String[] args) {
CircularLinkedList cll = new CircularLinkedList();
cll.addElementAtLast(10);
cll.addElementAtLast(20);
cll.printAll();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment