Insert the element at Start in Linked List in java.

class Node{
    int val;
    Node next;
    Node(int val){
        this.val=val;
    }
}
class Sll{
    Node head;
    Node tail;
    int size;
    void insertAtStart(int val){
      Node temp = new Node(val);    
        if(head==null) 
        head=tail=temp;
        else
        {
            temp.next=head;
            head=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);
    }
}
public class Implement {
    public static void main(String[] args) {
        Sll list = new Sll();
        list.insertAtStart(4);
        list.display();
        list.size();
        list.insertAtStart(3);
        list.display();
        list.size();
    }
}

output ->


size is= 1
3 4 
size is= 2

Comments

Popular posts from this blog

Introduction of java Programming language.

Stack data structure.