Runtime error when it's correct in my local machine


  • 0
    D

    Can anyone help me identify where the code goes wrong ?
    it is running fine on my local machine but leetcode oj complains the run time error

    class Solution {
    public:
        ListNode *deleteDuplicates(ListNode *head) {
            ListNode*p=head;
            ListNode*q=p->next;
            if (head==NULL||q==NULL) return head;
            while(q){
                if(q->val==p->val){
                    ListNode* t=q;
                    p->next=q->next;
                    q=q->next;
                    delete t;
                    
                }else{
                p=p->next;
                q=q->next;
                }
                
                
            }
            return head;
            // IMPORTANT: Please reset any member data you declared, as
            // the same Solution instance will be reused for each test case.
            
        }
    };

  • 0

    Could you format your code by selecting your code, and clicking on the {} button? Please read the FAQ for guidelines on asking a question.


  • 5
    P

    ListNode *q = p->next; This will result in runtime error when head is NULL

    class Solution {
    public:
        ListNode *deleteDuplicates(ListNode *head) {
            ListNode *p = head;
            if (head == NULL) // Check for head before reading p->next
                return head;
            ListNode *q = p->next;
            if (q==NULL)
                return head;
            while(q) {
                if(q->val==p->val) {
                    ListNode *t=q;
                    p->next=q->next;
                    q=q->next;
                    delete t;
                } else {
                    p=p->next;
                    q=q->next;
                }
            }
           return head;
        }
    };

  • 0
    G

    ListNode p=head;

    ListNode q=p->next;

    What if your head is null?


  • 0
    D

    right right right..I didn't think of that,thanks a lot!


  • 0
    D

    you are right..thanks for the note


  • 0
    L

    a more concise version:

    ListNode *deleteDuplicates(ListNode *head) {
        ListNode * iter = head;
        
        while (iter) {
            ListNode * runner = iter->next;
            while( runner && runner->val == iter->val)
                runner = runner->next;
            iter->next = runner;
            iter = runner;
        }
        
        return head;
    }

  • 0
    M

    nice nice nice


Log in to reply
 

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