Advertisement
ralphdc09

SinglyLinkedList-Ralph

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