Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.its101.prwk05_06;
- public class SinglyLinkedList {
- // node of the singly linked list
- public static class Node {
- String data;
- Node next;
- public Node(String data) {
- this.data = data;
- this.next = null;
- }
- }
- // declare head node and last node
- public Node head = null;
- public Node last = null;
- // createNode() creates new node to the list
- public void createNode(String data) {
- //Create a new node
- Node newNode = new Node(data);
- // checks if the linked list is empty
- if (head == null) {
- //If list is empty, both head and last node will point to new node
- head = newNode;
- last = newNode;
- } else {
- //newNode will be added after last node such that tail's next will point to newNode
- last.next = newNode;
- //newNode will become new last of the list
- }
- last = newNode;
- }
- // printNode() prints all the nodes in the list
- public void printNode() {
- // node current will point to head
- Node current = head;
- if (head == null) {
- System.out.println("List is empty");
- return;
- }
- System.out.println("Nodes of singly Linked List: ");
- while (current != null) {
- // prints each node by incrementing pointer
- System.out.print(current.data + " ");
- current = current.next;
- }
- System.out.println();
- }
- public static void main(String[] args) {
- SinglyLinkedList studentsList = new SinglyLinkedList();
- //Create new nodes to the Linked List and assign a data value
- studentsList.createNode("Ralph");
- studentsList.createNode("Espe");
- studentsList.createNode("Glen");
- studentsList.createNode("Nomer");
- //Prints the nodes-value of the Linked List
- studentsList.printNode();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement