Set / update the value in linked list in java.
■》 Code link-> click 👇👇👇
■》 Program->
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);
}
void Setdata(int idx,int num)throws Error{
Node trv=head;
if(head==null)
{
throw new Error("empty linked list");
}
if(idx==0){
head.val=num;
return ;
}
if(idx<0 || idx>=size){
throw new Error("invalid index");
}
for(int i=1; i<=idx; i++){
trv=trv.next;
}
trv.val=num;
}
}
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 and value to update =");
int ix=sc.nextInt();
int n=sc.nextInt();
list.Setdata(ix,n);
System.out.print("after update linked list is=");
list.display();
}
}
■》 Output->
5 6 7 8
enter the index and value to update =2
9
after update linked list is=5 6 9 8
Comments
Post a Comment