Click here to Skip to main content
15,877,966 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
adding element to the last using addLast method is throwing a null pointer exception.

What I have tried:

package dataStructures;

public class linkedlist {
   Node head;
	class Node{
		int data;
		Node next;
		
		  Node(int data) {
		    this.data = data;
		    this.next =null;
				
			}
	}
	
	public void addFirst(int data) {
		Node newnode = new Node(data);
		  
	
		if(head == null) {
			head = newnode;
			return;
			
		}
		else {
			newnode.next = head;
			head = newnode;
			return;
			
		}
		
	}
	
	public void addLast(int data) {
		Node newnode = new Node(data);
		if(head == null) {
			head = newnode;
			return;
		}
		
		Node currnode = head;
		
		while(currnode != null) {
			currnode = currnode.next;
		}
		try {
			 currnode.next = newnode;
		}
		catch(Exception e1){
			System.out.println("Exception occured in addLast method");
		}
		
		
	}
	
	public void printLlist() {
		if(head == null) {
			System.out.println("list is empty");
		}
		Node currnode = head;
		while(currnode != null) {
			System.out.print(currnode.data + " ");
			currnode = currnode.next;
		}
	}

	
	
	public static void main(String[] args) {
		linkedlist list = new linkedlist();
		
		list.addFirst(2);
		list.addFirst(6);
		list.addFirst(7);
		list.addLast(5);
		list.printLlist();
	}

}
Posted
Updated 28-Nov-22 0:14am

1 solution

Replace
Quote:
while(currnode != null) {
currnode = currnode.next;
}
try {
currnode.next = newnode; // here currnode is null
}


with
Java
while(currnode.next != null) {
			currnode = currnode.next;
		}
		try {
			 currnode.next = newnode;
		}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900