class TwoStacks { vector<int> elements; int ptr1, ptr2, capacity; TwoStacks(int capacity) { for(int i=0; i < capacity; i++) { elements.push_back(-1); } ptr1 = 0; ptr2 = capacity-1; this->capacity = capacity; } bool push1(int value) { if(ptr1 <= ptr2) { elements[ptr1] = value; ptr1++; } else { return false; } } bool push2(int value) { if(ptr1 <= ptr2) { elements[ptr2] = value; ptr2--; } else { return false; } } int pop1() { if(ptr1-1 < 0) { return -1; } ptr1--; return elements[ptr1]; } int pop2() { if(ptr2+1 >= capacity) { return -1; } ptr2++; return elements[ptr2]; } };
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter