1

I am trying to build a simple LinkedList in Java which takes chunks of a String. I am getting NullPointerException when i try to pop the elements. Below is my code. Please help me out.

public class LinkedList {

    private class Node {

        private String info;
        private Node next;

        Node() {
            this.info = null;
            this.next = null;
        }

        Node(String item, Node next) {
            this.info = item;
            this.next = next;
        }

    }

    // private Node start;

    Node start = new Node();
    Node end = new Node();
    Node top;

    public void addNode(String item) {
        if (start.next == null) {
            top = new Node(item, end);
            start.next = top;
            return;
        }

        if (start.next != null) {

            top.next = new Node(item, end);
            top = top.next;
            // top.next = end;

        }
    }

    public String[] pop() {
        String[] result = null;
        Node popping = start;
        while (popping.next != end) {
            popping = popping.next;
            int count = 0;
            System.out.println(count);
            result[count] = popping.info;

            count++;
        }

        return result;
    }

    public static void main(String args[]) {
        LinkedList kds = new LinkedList();
        for (String s : "kds on a roll".split(" ")) {
            kds.addNode(s);
            // System.out.println(kds.toString());
        }

        String[] s = null;
        System.out.println("Popping Begins");
        s = kds.pop();
        System.out.println(s);
    }
}
Kick Buttowski
  • 6,709
  • 13
  • 37
  • 58
  • 3
    Probably because `String[] result` is initialized to null – ryekayo Dec 30 '14 at 22:35
  • And also http://stackoverflow.com/questions/3988788/what-is-a-stack-trace-and-how-can-i-use-it-to-debug-my-application-errors?lq=1 – Alexis C. Dec 30 '14 at 22:36
  • 1
    @ryekayo I do not think this is rigth either Node() { this.info = null; this.next = null; }? – Kick Buttowski Dec 30 '14 at 22:38
  • @KickButtowski agreed, I only mentioned the result variable first since he was complaining about the pop() method – ryekayo Dec 30 '14 at 22:39
  • @ryekayo I guess at least info part has to have some default vale like empty? I think the cause of the issue is from the Node constructor? – Kick Buttowski Dec 30 '14 at 22:40
  • I havent put his code on the compiler to test it out, but could be possible. I know from experience though, initializing variables to null is just bad news – ryekayo Dec 30 '14 at 22:43

0 Answers0