0

I have been trying to create a method to add an element at the last of a LinkedList.But the code is giving me an error.It says -- "Cannot assign field "next" because "itNode" is null". How can i fix this?

 public void insertLast(String plateNum, int minutes) {
        
        Node nodeINLast = new Node(plateNum, minutes);
        nodeINLast.next = null;
        
        if(first == null) {
            first = nodeINLast;
        } else {
            Node itNode = first;
            while(itNode != null) {
                itNode = itNode.next;
            }
            itNode.next = nodeINLast;
        }
    }

I want to insert a node at the end of a linked list. I tried to insert elements at the first position it is working properly but I do not know why this is giving me a "Cannot assign field "next" because "itNode" is null" error.

wowonline
  • 1,061
  • 1
  • 10
  • 17

1 Answers1

0

since ItNode is null then you need the previous node of this one to point to the nodeInLast

Node nodeINLast = new Node(plateNum, minutes);
nodeINLast.next = null;

if(first == null){
    first = nodeINLast;
}
else{
    Node itNode = first;
    Node Temp = itNode;
    while(itNode!=null){
        Temp = itNode;
        itNode = itNode.next;
    }
    Temp.next = nodeINLast;
}

}