Don't know what was wrong,please help my c++ code


  • 0
    V
      class Solution {
        public:
            ListNode* removeElements(ListNode* head, int val) {
                ListNode *prehead=new ListNode(-1);
                prehead->next=head;
                ListNode *current=prehead;
                ListNode *tmp=prehead->next;
                while(tmp)
                {
                    while(tmp->val==val)
                        tmp=tmp->next;
                    current->next=tmp;
                    current=current->next;
                    tmp=current->next;
                }
                return prehead->next;
            }
        };
    

    when the testcase is [1] 1,or [1,1] 1,or [1,1,...]1 ,the code status is wrong time error.


  • 0
    E

    In the inner while loop tmp becomes NULL after calling tmp=tmp->next, but you are still checking
    tmp->val==val for a NULL tmp pointer. You should check if tmp is NULL in this inner while.


  • 0
    V

    Thanks a lot.And tmp=current->next has the same mistake as you mentioned.


Log in to reply
 

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