在Java中将元素附加到列表的末尾

时间:2020-07-28 06:41:04

标签: java list append

我正在分配一个作业,以创建一个列表,该列表没有泛型的最大元素数。在将泛型添加到代码之前,我想先使用基本int进行尝试。但是,每当我调用append()方法时,我都会不断收到NullPointerException。这是代码:

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);
    }

我知道其背后的逻辑有点像Python风格,但是我以前从未研究过Python,我需要帮助了解为什么while循环会导致NullPointerException每次使我的程序崩溃?

0 个答案:

没有答案
相关问题