a stupid solution


  • 0
    X
        ListNode* removeElements(ListNode* head, int val) {
              ListNode *pre_node=head,*next_node=NULL,*old_pre_node=head;
    	      while(pre_node){
    		       next_node=pre_node->next;
    		       if(pre_node->val==val&&pre_node==head){  //head
    		            ListNode *t=head;
    			        head=next_node;
    			        delete t;
    		       }
    		       else if(pre_node->val==val&&pre_node!=head){
    			         old_pre_node->next=next_node;
    			         delete pre_node;
    			         pre_node=NULL;
    		       }
    		       if(pre_node!=NULL){  //if pre_node been deleted,then keep the old_pre_node unchanged
    		         	old_pre_node=pre_node;
    			   pre_node=next_node;  
    	      }
    	      return head;
        }
    

Log in to reply
 

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