0

I am trying to delete all those elements with a specific value. Here's my code. This code is not working. Can someone help me? TIA. Example Given: 1 --> 2 --> 6 --> 3 --> 4 --> 5 --> 6, val = 6 Return: 1 --> 2 --> 3 --> 4 --> 5

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

public class Solution {
public ListNode removeElements(ListNode head, int val) {
    if(head == null){
        return null;
    }
    ListNode curr = head;
    ListNode prev = null;
    while(curr != null){

        if(curr.val == val){
            prev.next = curr.next; 
        }
        else{
            prev = curr;
          }
          curr = curr.next;
    }
    return head;
}
}
chan
  • 274
  • 1
  • 5
  • 24
  • Can you post the stack trace? – itsmichaelwang Jul 20 '17 at 04:27
  • The `NullPointerException` tells you what line is causing the problem. Look for that line, see what you're doing on that line, and in particular see where referring to `x.something` where `x` could be `null`. Once you've narrowed it down, you should be able to figure out the problem. – ajb Jul 20 '17 at 04:29
  • Please post the complete execution code as well(main method), as well as the error displayed in console, will be easy to track down the issue. – nobalG Jul 20 '17 at 04:35
  • @Jim Garrison Really? I dont think that the OP is asking for 'What is nullpointer and how to fix it'. You seemed to be marking it as duplicate without even going through the problem. – nobalG Jul 20 '17 at 05:46
  • @nobalG The original version of the question said "I am getting a nullpointer exception". Click the "edited xx hours ago" link to see it. The edit changes that to "the code is not working", which is off-topic as well. – Jim Garrison Jul 20 '17 at 16:03
  • StilL @JimGarrison yea I know that, but still the core question was something else and can be easily interpreted by going through the problem explained in the passage. May be question quality was low, but the sentence passed by you was not in accordance with the crime( it was not duplicate). Why I am concerned so much? Because thats how new users loose interest on this platform, and i dont want them to get disappointed for the 'wrong' they never did,. :) – nobalG Jul 20 '17 at 16:05

0 Answers0