Linkedlist

mail@pastecode.io avatar
unknown
c_cpp
2 years ago
1.2 kB
2
Indexable
Never
ListNode* stockPriceChange(ListNode* head , int x) {
    if(head == NULL || head->next == NULL)  return head;

    ListNode *smaller = new ListNode(-1);
    ListNode *sp = smaller;

    ListNode *larger = new ListNode(-1);
    ListNode *lp = larger;

    ListNode *cur = head;
    ListNode *pivot = NULL;
    //ListNode *pivotHead = NULL;
    ListNode *pivotEnd = NULL;
    bool isPresent = false;

    while(cur != NULL){
        if(cur->val == x){            
            if(isPresent){
                pivotEnd->next = cur;
                pivotEnd = cur;
            }else{
                pivot = cur;
                pivotEnd = cur;
                isPresent = true;
            }                        
        }else if(cur->val < x){
            sp->next = cur;
            sp = sp->next;
        }else{
            lp->next = cur;
            lp = lp->next;
        }
        cur = cur->next;
    }

   if(isPresent){
        lp->next = NULL;
        sp->next = pivot;
        pivotEnd->next = larger->next;
   }else{
        lp->next = NULL;
        sp->next = larger->next;
   }

    return smaller->next;
}