Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.its101.prwk05_06;
- public class CircularLinkedList {
- // Node of the circular linked List
- public static class Node {
- String data;
- Node next;
- public Node(String data) {
- this.data = data;
- }
- }
- // declare head node and last node
- public Node head = null;
- public Node last = null;
- // createNode() add new node at the end of the linked list
- public void createNode(String data) {
- // create new node
- Node newNode = new Node(data);
- // check if the linked list is empty
- if (head == null) {
- // if linked list is empty, head node and last node will point to new node
- head = newNode;
- last = newNode;
- newNode.next = head;
- } else {
- // last node will point to new node
- last.next = newNode;
- // new node will become new last node
- last = newNode;
- // last node will point to head node to become circular linked list
- last.next = head;
- }
- }
- // printNode() prints the nodes in the linked list
- public void printNode() {
- Node current = head;
- if (head == null) {
- System.out.println("Circular Linked List is empty!");
- } else {
- System.out.println("Nodes of the circular Linked List: ");
- do {
- // print each node by incrementing to current node pointer
- System.out.print(" " + current.data);
- current = current.next;
- } while (current != head);
- System.out.println();
- }
- System.out.println();
- }
- public static void main(String[] args) {
- CircularLinkedList studentsList = new CircularLinkedList();
- //Create new node to the linked list and assign a data value
- studentsList.createNode("Ralph");
- studentsList.createNode("Espe");
- studentsList.createNode("Glen");
- studentsList.createNode("Nomer");
- //Print the nodes-value of the Linked List
- studentsList.printNode();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement