Advertisement
ralphdc09

CircularLinkedlist_Ralph

Oct 25th, 2021
63
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.14 KB | None | 0 0
  1. package com.its101.prwk05_06;
  2.  
  3. public class CircularLinkedList {
  4.     // Node of the circular linked List
  5.     public static class Node {
  6.         String data;
  7.         Node next;
  8.  
  9.         public Node(String data) {
  10.             this.data = data;
  11.         }
  12.     }
  13.     // declare head node and last node
  14.     public Node head = null;
  15.     public Node last = null;
  16.  
  17.     // createNode() add new node at the end of the linked list
  18.     public void createNode(String data) {
  19.         // create new node
  20.         Node newNode = new Node(data);
  21.         // check if the linked list is empty
  22.         if (head == null) {
  23.             // if linked list is empty, head node and last node will point to new node
  24.             head = newNode;
  25.             last = newNode;
  26.             newNode.next = head;
  27.         } else {
  28.             // last node will point to new node
  29.             last.next = newNode;
  30.             // new node will become new last node
  31.             last = newNode;
  32.             // last node will point to head node to become circular linked list
  33.             last.next = head;
  34.         }
  35.     }
  36.  
  37.     // printNode() prints the nodes in the linked list
  38.     public void printNode() {
  39.         Node current = head;
  40.         if (head == null) {
  41.             System.out.println("Circular Linked List is empty!");
  42.         } else {
  43.             System.out.println("Nodes of the circular Linked List: ");
  44.             do {
  45.                 // print each node by incrementing to current node pointer
  46.                 System.out.print(" " + current.data);
  47.                 current = current.next;
  48.             } while (current != head);
  49.             System.out.println();
  50.         }
  51.         System.out.println();
  52.     }
  53.  
  54.     public static void main(String[] args) {
  55.         CircularLinkedList studentsList = new CircularLinkedList();
  56.  
  57.         //Create new node to the linked list and assign a data value
  58.         studentsList.createNode("Ralph");
  59.         studentsList.createNode("Espe");
  60.         studentsList.createNode("Glen");
  61.         studentsList.createNode("Nomer");
  62.  
  63.         //Print the nodes-value of the Linked List
  64.         studentsList.printNode();
  65.     }
  66. }
  67.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement