Share my java answer 353ms


  • 0
    C

    create a prehead in order to save head for return..

    public class Solution {
    public ListNode removeElements(ListNode head, int val) {
        if(head==null) return head;
    	ListNode prehead=new ListNode(-1);
    	prehead.next=head;
    	ListNode p=prehead;
    	//everytime check if p.next should be removed..
    	//until p.next==null..
    	//p is always being checked.
    	while(p.next!=null){
    		if(p.next.val==val){
    			//remove p.next
    			p.next=p.next.next;
    		}else{
    			//move one step forward
    			p=p.next;
    		}	
    	}
    	return prehead.next;
    
    }
    

    }`


  • 0
    J

    Hi. Thank you for your answer. I have a question about the return value. My solution is to try to return p.next not prehead.next, and it doesn't work. So could you please explain it a little bit?

    Thank you!


  • 0
    C

    your p.next will be null at the end of while loop.


Log in to reply
 

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