In: Computer Science
Write a Java program to implement a Single Linked List that will take inputs from a user as Student Names.
First, add Brian and Larry to the newly created linked list and print the output
Add "Kathy" to index 1 of the linked list and print output
Now add "Chris" to the start of the list and "Briana" to the end of the list using built-in Java functions.
Print the output of the linked list.
Program Code Screenshot :
Sample Output :
Program Code to Copy
class SingleLinkedList{ //Node of the linked list class Node{ Node next; String s; //Argumented constructor Node(String s){ this.s = s; } @Override public String toString(){ return this.s; } } //Head of the linked list Node head; SingleLinkedList(){ head = null; } //Add a String to the linked list public void add(String s){ //If head is null, make the new node head if(head==null){ head = new Node(s); return; } //Move to the end of the linked list Node temp = head; while (temp.next!=null){ temp = temp.next; } //Add new node at the end temp.next = new Node(s); } public void add(int index, String s){ Node newNode = new Node(s); //If index is 0, add at the head if(index==0){ newNode.next = head; head = newNode; return; } //Move till the index Node temp = head; for(int ind=0;ind<index-1;ind++){ temp = temp.next; } newNode.next = temp.next; temp.next = newNode; } public String toString(){ Node temp = head; String ans = ""; while (temp!=null){ ans = ans+temp.toString()+"->"; temp = temp.next; } ans = ans+"NULL"; return ans; } } class Main{ public static void main(String[] args) { SingleLinkedList sl = new SingleLinkedList(); sl.add("Brian"); sl.add("Larry"); System.out.println(sl); sl.add(1,"Kathy"); System.out.println(sl); sl.add(0,"Chris"); sl.add("Briana"); System.out.println(sl); } }