0

I'm having this problem with my linked list that when i try to access the last node data section it throws me a null exception

the code section: getlast() method with an object in the main class

package lab1_ds;
    public class LAB1_DS {
        public static void main(String[] args) {
               singlylinkedlist mylist=new singlylinkedlist();
            singlylinkedlist<person> plist=new singlylinkedlist();
            plist.addfirst(new person("Hesssa","SA"));
            plist.addfirst(new person("Nora","SA"));
            plist.display();
            plist.addnode(new person("Farah","SA"),2);
             plist.display();
             System.out.println(plist.first().getName());
             plist.removeNode(plist.getlast());
             plist.display();
        }

    }

and the linked list code is:

package lab1_ds;
public class singlylinkedlist <E>{
    private static class Node<E>{
        private E element;
        private Node<E> next;

        public Node(E element, Node<E> next) {
            this.element = element;
            this.next = next;
        }

        public E getElement() {
            return element;
        }

        public Node<E> getNext() {
            return next;
        }

        public void setNext(Node<E> next) {
            this.next = next;
        }

    }
    private Node<E> head=null;
    private Node<E> tail=null;
    private int size=0;

    public singlylinkedlist() {
    }
    public void display(){
         Node<E> current;
         current=head;
         int count=0;
         System.out.println("\n-----------Display method-----------");
         while(current!=null){
             count++;
              System.out.println("Linked list ("+count+"):"+current.getElement());
              current=current.getNext();

         }
    }
    public int size(){
        return size;
    }
    public boolean isEmpty(){
        return size==0;
    }
    public E getlast(){
        if (isEmpty())  
            return null;
        return tail.getElement(); 
    }




    public void setTail(Node<E> tail) {
        this.tail = tail;
    }

     public E first(){
        if (isEmpty())
            return null;
        return head.getElement();      
    }
    public void addfirst(E value){
         Node<E> newNode= new Node(value,null);
         newNode.next=head;
         head=newNode;
         size=size+1;
         if(size==1)
             head=tail;
    }
    public void addlast(E value){
        Node<E> newNode= new Node(value,null);
        if(size==0)
            head=tail=newNode;
        else{  tail.next=newNode;
        tail=newNode;
        }
        size=size+1;
    }
    public void addnode(E value,int pos){
        Node<E> current;
     if(pos==1)
         addfirst(value);
      if(pos==size+1)
         addlast(value);
       Node<E> newNode= new Node(value,null);
       current=head;
       int count=1;
    while(count<pos-1 && current.next!=null){
        current=current.next;
        count=count+1;
    }
    newNode.next=current.next;
    current.next=newNode;
    size++;//or size=size+1;

    }
     public void removeFirst(){
         if (isEmpty()){
             System.out.println("linked list is empty");
             return;
         }
         head=head.getNext();
         size--;//or size=size-1;
         if(size==0)
             tail=null;//only node

     }
      public void findNode(E place){
           if (isEmpty()){
             System.out.println("linked list is empty");
             return;
         }
          Node<E> current=head;
          int count=1;
          while (current!=null ){
              if(current.getElement()==place || current.getElement().equals(place)){
                   System.out.println("found in posittin #"+count);
              return;}
               count++;
          current=current.getNext();
          }//end while loop

          System.out.println("\n.......Node is not found!......");
      }
      public void removeNode(E place){
          Node<E> current=head;
         Node<E> prev=head;
            if (isEmpty()){
             System.out.println("linked list is empty");
             return;
         }
            while(current.getElement()!=place && !current.getElement().equals(place)){
                if(current.next==null){
                    System.out.println("\n not found...");
                    return;
                }
                prev=current;
                current=current.next;
            }//end loop
            if(current==head){
                removeFirst();
            }
            else {
                prev.next=current.next;
                size--;
            }
            if(current==tail){//node i'm trying to remove is the last node 
                tail=prev;
            }
      }
}

and the error shows:

Exception in thread "main" java.lang.NullPointerException
at lab1_ds.singlylinkedlist.getlast(singlylinkedlist.java:52)
    at lab1_ds.LAB1_DS.main(LAB1_DS.java:34)

line 52:

  return tail.getElement(); 

line 34:

plist.removeNode(plist.getlast());

Please help me I can't seem to figure it out and the lab assisstant says it should work (the getlast())

  • 3
    It may not be the only issue, but I believe that in `addFirst`, `head=tail` should be `tail=head`. – Eran Feb 04 '20 at 09:04
  • @rghome it doesn't unfortunately – Meme Mohammad Feb 04 '20 at 09:10
  • [What is a debugger and how can it help me diagnose problems?](https://stackoverflow.com/q/25385173/5221149) – Andreas Feb 04 '20 at 09:23
  • @MemeMohammad this is a duplicate of [What is a NullPointerException, and how do I fix it?](https://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it) – seenukarthi Feb 04 '20 at 09:24

1 Answers1

1

The problem is in your addfirst method. You are reassigning head to null, rather than tail to head. Correct version:

public void addfirst(E value) {
        Node<E> newNode = new Node(value, null);
        newNode.next = head;
        head = newNode;
        size = size + 1;
        if (size == 1)
            tail = head;
    }

After this change, the output is:

-----------Display method-----------
Linked list (1):person{name='Hesssa', state='SA'}

-----------Display method-----------
Linked list (1):person{name='Nora', state='SA'}
Linked list (2):person{name='Hesssa', state='SA'}

-----------Display method-----------
Linked list (1):person{name='Nora', state='SA'}
Linked list (2):person{name='Farah', state='SA'}
Linked list (3):person{name='Hesssa', state='SA'}
Nora

-----------Display method-----------
Linked list (1):person{name='Nora', state='SA'}
Linked list (2):person{name='Farah', state='SA'}

Sidenote:

Please see the naming convention of classes and methods. They should be in snake case. For example, method name from addfirst -> addFirst. Class name from singlylinkedlist -> SinglyLinkedList

Shafiul
  • 1,452
  • 14
  • 21
  • Thank you! it worked you are a lifesaver!! as for the sidenote yeah I know the naming should be like that but I'm too lazy to do it like that :p but thank you again!! – Meme Mohammad Feb 04 '20 at 12:55