Accepted C Solution Rt O(n) Sp(1) with little explanation


  • 0
    R
    struct ListNode* removeElements(struct ListNode* head, int val) {
       	if(NULL == head) return head;
    
    	struct ListNode *p=head; 
    	struct ListNode *pre=NULL; 
    	
    	while(NULL != p){
    		if(p->val == val){
    			struct ListNode *del =p;
    			p=p->next;
    			if(NULL!=pre){
    				pre->next=p;
    			}else{
    				head=p;
    			}
    			free(del);
    		} else{
    			pre=p;
    			p=p->next;
    		}
    	}
    
    	return head;
    }
    

    well,it's quite an easy linked-list-manipulation method.


Log in to reply
 

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