Easy to understand C++ code with comments


#1
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
ListNode* Solution::partition(ListNode* A, int B) {
    ListNode *l1,*p1,*l2,*p2,*i = A;
    //l1 is a list of values < B. l2 has values > B
    //p1 and p2 are the end of l1 and l2 lists
    //initially set dummy nodes for all else they point to NULL
    l1 = p1 = new ListNode(0);
    l2 = p2 = new ListNode(0);
    
    while(i != NULL){
        if(i->val < B){
            p1->next = i;
            p1 = p1->next;
        } else {
            p2->next = i;
            p2 = p2->next;
        }
        i = i->next;
    }
    p2->next = NULL;
    p1->next = l2->next; //to avoid joining with l2's dummy variable
    return l1->next; //again, to avoid dummy variable of l1
}

#2
 if(i->val < B){
            p1->next = i;
            p1 = p1->next;
        }

in the if part if I am doing “p1 = i;” instead of " p1->next = i;" it is showing run time error, can anyone explain why is this happening.