Pregunta

I was curious as to learn how you would add multiple ints to a Node in a LinkedList in java (single circular). I had found a thread on SO and was reading on it but wasn't sure exactly how it worked. Thought I would revive the question to see if I can get an answer.

This is my Node class

public class LinkedList{
private class Node{
    private int pid;
    private int time;
    private Node next;

    public Node(int pid, int time){
        this.pid=pid;
        this.time=time;
    }
}
int size;
Node head;

This is my add which I'm just trying before I do any remove or anything like that.

public void add(int pid, int time) {
    Node curr=head;
    Node newNode=new Node(pid, time);
    if(head==null){
        head=newNode;
            newNode.next=head;
    }//end if
    else{
        while(curr.next!=head){
            curr = curr.next;
        }//end while
        curr.next=newNode;
            newNode.next=head;
    }//end else
    size++;
}//end add
}

This is what I have so far but when I try to input the two ints I get a null pointer exception at the private int time Am I doing something wrong? I'm reading in a file and then storing the two ints in a single node and then doing the same until the file is completely read through. I have the file reading in just fine and I have the two ints stored as ints from the file but I can't seem to get it to store the ints in the Node quite yet

¿Fue útil?

Solución

How have you initialized head? Did you do Node head = new Node()?

If you make a custom constructor, Java does not add the default constructor anymore. You have to define that again.

You can instead do Node head = null;

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top