Search code examples
javacollectionslinked-listsingly-linked-list

Why my Single Linked List implementation is giving me my first element twice after adding objects?


Here i am trying to implement the basic operations of "Single Linked List". But only here i am facing only one problem that is, after adding elements, i.e.

al.add("Ravi");
al.add("Vijay");
al.add("Sanjay");
al.add("Ajay"); 

I am getting output as:
[]--------->For empty Linked list
[Ravi,Ravi,Vijay,Sanjay,Ajay]------>After adding elements.

class MyLinkedList {
        private Node first;
        private Node last;
        private int count;

        public void add(Object ele){
            if(first==null){
                first=new Node(ele);
                last=first;
                count++;
            }
            last.next=new Node(ele);
            last=last.next;
            count++;
        }
        public int size(){
            return count;
        }
        public Object get(int index){
            if(index>=size())throw new IndexOutOfBoundsException();
            Node p=first;
            for(int i=0;i<=index;i++){
                p=p.next;
            }
            return p.ele;
        }
        public void remove(int index){
            if(index>=size())throw new IndexOutOfBoundsException();
            if(index==0){
                first=first.next;
                count--;
                return;
            }
        }

        @Override
        public String toString() {
            if(size()==0)return "[]";
            Node p=first;
            String s="[" + p.ele;
            while(p.next!=null){
                p=p.next;
                s+=","+p.ele;
            }
            return s + "]";
        }

        private class Node{
            Object ele;
            Node next;
            Node(Object ele){
                this.ele=ele;
            }
        }

        public static void main(String[] args) {
             MyLinkedList al=new MyLinkedList(); 
             System.out.println(al);
              al.add("Ravi");  
              al.add("Vijay");  
              al.add("Sanjay");  
              al.add("Ajay");
              System.out.println(al);

        }

    }

Solution

  • Because you add it twice:

        public void **add**(Object ele){
            if(first==null){
                first=new Node(ele); //First
                last=first;
                count++;
            }
            last.next=new Node(ele); //second.
            last=last.next;
            count++;
        }
    

    add an else Statement:

        public void **add**(Object ele){
            if(first==null){
                first=new Node(ele);
                last=first;
                count++;
            } else {
              last.next=new Node(ele);
              last=last.next;
              count++;
            }
        }