Seg fault: please help


#1

ListNode* Solution::subtract(ListNode* node) {

if(node==NULL || node->next == NULL){
    cout << "returning earliest\n";
    return node;
}

// int a=1;
// int b=1;
cout << "creating tmp...\n";
ListNode* tmp=node;
cout << "tmp data at creation:" << tmp->val << endl;



while(tmp->next){
    // b++;
    cout << tmp->val <<endl;
    tmp = tmp->next;
}
cout << tmp->val << endl;
if(tmp->next == NULL){
    cout << "tmp at last\n";
}


// int count=0;
ListNode *from,*to;

to = node; // first
from = tmp; // last


while( from != to || (to->next) != from ){
    to->val = from->val - to->val;


    tmp = to;
    while(tmp->next != from)
        tmp = tmp->next;

    from = tmp;
    to = to->next;

}
return node;

}


#2
while(tmp->next){
    // b++;
    cout << tmp->val <<endl;
    tmp = tmp->next;
}
```in this loop ,you should be checking for null condition of tmp instead of tmp->next. It will give segmentation error at the last node,