Whats wrong with this?


  • -1
    N

    I keep getting the below message, when I submit my code.
    Runtime Error Message:
    Line 27: java.lang.NullPointerException
    Last executed input:
    [0,1], node at index 0 (node.val = 0)

    class DeleteNode{
    ListNode head;
    public class ListNode {
    int val;
    ListNode next;
    ListNode(int x) { val = x; }
    }

    public void deleteNode(ListNode node) {
        if(node == null){
        	System.out.println("Invalid delete node request. List is empty");
        }
    
        ListNode tmp = head;
        if (node == tmp){
        	head = head.next;
        	printList(head);
        	return;
        }
       
        ListNode prev = null;
    
        while(node != tmp){
        	prev = tmp;
        	tmp = tmp.next;
        }
    
        prev.next = tmp.next;
        printList(head);
    }
    
    public ListNode addNode(int data){
    	ListNode tmp, tmp1;
    	tmp = head;
    	if (tmp == null){
    		head = new ListNode(data);
    		tmp = head;
    		return tmp;
    	}
    	else{
    		while(tmp.next != null){
    			tmp = tmp.next;
    		}
    		tmp1 = new ListNode(data);
    		tmp.next = tmp1;
    		return tmp1;
    
    	}
    
    }
    
    
    public void printList(ListNode head){
    	ListNode tmp;
    	tmp = head;
    	if (tmp == null){
    		System.out.println("List is empty");
    	}
    	else{
    		while(tmp != null){
    			System.out.println(tmp.val);
    			tmp = tmp.next;
    		}
    	}
    }
    
    public static void main(String argsp[]){
    	DeleteNode s = new DeleteNode();
    	ListNode head, s1, s2;
    	head = s.addNode(0);
    	s2 = s.addNode(1);
    	
    	s.printList(head);
    	s.deleteNode(head);
    	
    }
    

    }


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.