Delete an element from a given Index in linked list in java.

■》 Code link🔗 -> click👇👇👇

https://www.programiz.com/online-compiler/6fkgrxG1pyevE

■》Program->

 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 deleteAtIndex(int idx)throws Error{

        if(idx==0){

        head=head.next;

        return;

        }

        if(idx<0 || idx>=size){

        throw new Error("invlaid index");

        }

        Node temp=head;

        for(int i=1; i<=idx-1; i++){

            temp=temp.next;

        }

        if(temp.next==tail) tail=temp;

        temp.next=temp.next.next;

        size--;

    }

}

public class Implement {

    public static void main(String[] args) {

        Sll list = new Sll();

        list.insertAtEnd(5);

        list.insertAtEnd(6);

        list.insertAtEnd(7);

        list.insertAtEnd(8);

        list.display();

        System.out.println("after delete linked list=");

        list.deleteAtIndex(3);

        list.display();

    }

}


■》 Output->


5 6 7 8

after delete linked list=

5 6 7 

Comments

Popular posts from this blog

Introduction of java Programming language.

Stack data structure.