0

I'm working an assignment to create a list with no maximum number of elements with generics. Before I add a generic to my code, I wanted to try it with a basic int first. However, I keep getting a NullPointerException whenever I make a call to my append() method. Here's the code:

public class PythonList {
    class Node {
        int data;
        Node next;
        
        public Node(int data) {
            this.data = data;
            next = null;
        }
    }
    Node head;
    public void append(int x) {
        Node currentNode = head;
        Node tempNode = new Node(x);

        while(currentNode.next != null) {
            currentNode = currentNode.next;
        }
        currentNode.next = tempNode;
    }
    public static void main(String[] args) {
        PythonList list = new PythonList();
        list.append(1);
        list.append(2);
        list.append(3);
        list.append(4);
    }

I know the logic behind this is sort of in the style of Python, but I've never studied Python before, and I need help understanding why the while loop causes a NullPointerException that crashes my program every time?

Arjun Singh
  • 103
  • 2
  • 7

0 Answers0