0

I am trying to implement data structure Linked List (Singly) however by adding elements returns NULLPOINTEREXCEPTION.

import java.util.NoSuchElementException;

public class Linkedlist<ANYTYPE>{

private Node head;

Linkedlist(){
    head = null;
}

public void add(ANYTYPE data){
    head.next = new Node<>(data, head);
}

public void traverse(){
    if(head == null) throw new NoSuchElementException("List may be empty");

    Node temp = head;

    while(temp != null){
        System.out.println(temp.data+" ");
        temp = temp.next;
    }
}

public static void main(String[] args) {

    Linkedlist<String> l=new Linkedlist<String>();
    l.add("one");
    l.add("two");
    l.traverse();
}


private class Node<ANYTYPE>{

    private ANYTYPE data;
    private Node next;

    Node(ANYTYPE data, Node next){
        this.data = data;
        this.next = next;
    }
}

}
Rahul
  • 76,197
  • 13
  • 71
  • 125

2 Answers2

0

Yeah cause in your constructor you are setting head to null as seen below

Linkedlist(){
    head = null;
}

Then in Add() trying to do head.next and so the exception

public void add(ANYTYPE data){
    head.next = new Node<>(data, head);
}
Rahul
  • 76,197
  • 13
  • 71
  • 125
0

In the add() method, you'll have to check if there is any node yet (as you correctly do in the traverse() method). if (head == null), you cannot access the .next member. Instead, your first element to add should be assigned to head itself.

Florian
  • 255
  • 1
  • 9
  • Thanks Rahul, Florian I added null check if head is empty in each method. public void add(ANYTYPE data) { if (head == null) head = new Node(data, null); head = new Node<>(data, head); } – Anand Kulkarni May 01 '16 at 09:09