试图找出链表的大小空指针错误

时间:2019-01-06 05:27:33

标签: java linked-list

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

ffmpeg -y -f dshow -i video=FFsource:audio=Stereo Mix (Realtek High Definition Audio) -vcodec libvpx -acodec libvorbis -threads 0 -b:v 3300k -cpu-used 5 -keyint_min 150 -g 150 -map 0 -flags:v +global_header -f nut pipe:

}

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

我想弄清楚链表的大小,并能够在最后添加节点。

2 个答案:

答案 0 :(得分:2)

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

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

答案 1 :(得分:2)

您正在更改head参考,由于该参考输出不正确。您应该使temp引用head,并使用temp进行操作,这不会影响head。如下所示:

public class LinkedList {
    Node head;

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

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

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

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


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

class Node {
    int data;
    Node next;

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