java - 试图计算出链表空指针错误的大小

标签 java linked-list

对于下面的代码,我想知道为什么链表的大小总是给我一个空指针异常,为什么我的pushEnd方法在末尾推送一个新节点不起作用,它在几个之后添加一个元素节点并摆脱休息。

class Node {
int data;
Node next;
Node(int data){
    this.data = data;
}

}

public class LinkedList {
Node head;  

/* Inserts a new Node at front of the list. */
public Node push(int data) 
{ 
    Node newNode = new Node(data); 
    newNode.next = head; 
    return head = newNode; 
}

public Node pushEnd(int data) {
    Node newNode = new Node(data);
    if (head == null) {
        head = newNode;
    }

    newNode.next = null;

    while(head != null) {
        head = head.next;
        head.next = newNode;
        return newNode;
        }
    return head;
}

public int getSize() {
    int size = 0;
    while(this.head != null) {
        size++;
        head = head.next;
    }
    return size;
}


public void printList() {
    while (this.head !=null) {
        System.out.print(head.data + "-->");
        head = head.next;
    }       
    System.out.println(head);
}

}

public class Tester {


public static void main(String[] args) {

    LinkedList ll = new LinkedList();

    ll.push(35);
    ll.push(100);
    ll.push(14);
    ll.push(44);
    ll.push(10);
    ll.push(8);


    System.out.println("Created Linked list is:"); 
    ll.printList(); 



    System.out.println(ll.getSize());

}

}

我想计算出链表的大小并能够在末尾添加节点。

最佳答案

您的while循环直接修改head变量。这会导致您的其他代码失败,因为现在 head 指向列表中的最后一个节点。

创建一个新的局部变量以在 while 循环中使用(而不是直接修改 head)。这应该可以解决问题!

关于java - 试图计算出链表空指针错误的大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54058886/

相关文章:

java - 如何从 Spring Data 存储库调用 MySQL 函数

java - 如何加入两个与 JPA/Hibernate 的关联

java - "Serializable"类中的字段应该是 transient 的或可序列化的

c - 从队列中使用 dequeue 方法时抛出异常

java - 链表抛出 IndexOutOfBoundsException

c - 替换链表中的节点值

java - 尽管出现了 fragment 内容,但工具栏内容并未出现

java - 类似 STL 的 Java 红黑树/TreeSet/Map 和带有非快速失败/安全迭代器的链表

c++ - 双向链表的实现

java - 如果您不声明主键,为什么它不会在数据库中创建表?