Untitled

 avatar
user_6347851
plain_text
a year ago
2.4 kB
5
Indexable
public class LinkedList {
    public static class Node {
        int data;
        Node next;
        public Node(int data) {
            this.data = data;
            this.next = null;
        }
    }
        public static Node head;
        public static Node tail;
        public static int size;

        public void addFirst(int data){
            Node newNode = new Node(data);//constructor
            size++;
            if(head==null){
                head=tail=newNode;
                return;
            }
            newNode.next=head;//linking with existing head
            head=newNode;//initializing new head
        }

        public void addLast(int data){
            Node newnode=new Node(data);
            size++;
            if(head==null){
                head=tail=newnode;
                return;
            }
            tail.next=newnode;
            tail=newnode;
        }

        public void addMiddle(int index ,int data){
            Node newnode=new Node(data);
            size++;
            Node temp=head;
            int i=0;
            while (i<index-1){
                temp=head.next;
                i++;
            }
            newnode.next=temp.next;
            temp.next=newnode;
        }

        public void removeFirst(){
            if(size==1){
                head=tail=null;
            }
            head=head.next;
            return;
        }

    public void removeLast(){
        if(size==1){
            head=tail=null;
        }
        Node prev=head;
        for (int i = 0; i < size-2; i++) {
            prev=prev.next;
        }
        prev.next=null;
        tail=prev;
        return;
    }

        public static void printll(LinkedList ll){
            Node temp=head;
            while(temp!=null){
                System.out.print(temp.data);
                temp=temp.next;
            }
            System.out.println();
        }
    public static void main(String[] args) {
        LinkedList ll=new LinkedList();
        ll.addFirst(1);
        ll.addFirst(2);
        ll.addLast(3);
        ll.addLast(4);
        printll(ll);
        ll.addMiddle(2,5);
        printll(ll);
        System.out.println(size);
        ll.removeFirst();
        printll(ll);
        ll.removeLast();
        printll(ll);
    }
}
Editor is loading...
Leave a Comment