Simplest C++ solution with stack and a flag


#1
ListNode* Solution::solve(ListNode* A, int B) {
    ListNode* iter;
    ListNode* prev;
    bool doreverse=true;
    int i;
    stack<int> reverse;
    for(i=1,iter=A,prev=A;iter!=NULL;i++,iter=iter->next){
        if(i%B==0){
            reverse.push(iter->val);
            if(doreverse){
                while(prev!=iter->next){
                    prev->val=reverse.top();
                    reverse.pop();
                    prev=prev->next;
                }   
                doreverse=false;
            }else{
                while(reverse.empty()){
                    reverse.pop();
                }
                prev=iter->next;
                doreverse=true;
            }
        }else{
            reverse.push(iter->val);
        }
    }
    return A;
}