{}
run-icon
Main.java
import java.util.Scanner; class Node{ int val; Node next; Node(int val){ this.val=val; } } class Sll{ Node head; Node tail; int size; void insertAtEnd(int val){ Node temp = new Node(val); if(head==null) head=tail=temp; else { tail.next=temp; tail=temp; } size++; } void display(){ Node temp=head; while(temp!=null) { System.out.print(temp.val+" "); temp=temp.next; } System.out.println(); } void size(){ System.out.println("size is= "+size); } int getdata(int idx)throws Error{ Node trv=head; if(head==null) { throw new Error("empty linked list"); } if(idx==0){ return head.val; } if(idx<0 || idx>=size){ throw new Error("invalid index"); } for(int i=1; i<=idx; i++){ trv=trv.next; } return trv.val; } } public class Implement { public static void main(String[] args) { Scanner sc =new Scanner(System.in); Sll list = new Sll(); list.insertAtEnd(5); list.insertAtEnd(6); list.insertAtEnd(7); list.insertAtEnd(8); list.display(); System.out.print("enter the index no. to retrieve value="); int n=sc.nextInt(); System.out.print("the value is= "+list.getdata(n)); } }
Output