void pop() { if (nTime % 2) { while (!one.empty()) { T t = one.front(); one.pop(); if (!one.empty()) { two.push(t); } } } else { while (!two.empty()) { T t = two.front(); two.pop(); if (!two.empty()) { one.push(t); } } }
nTime = (nTime + 1) % 2; --nSize; }
T& top() { if (nTime % 2) { while (!one.empty()) { T t = one.front(); one.pop(); if (!one.empty()) { two.push(t); } else { two.push(t); nTime = (nTime + 1) % 2; return two.back(); } } } else { while (!two.empty()) { T t = two.front(); two.pop(); if (!two.empty()) { one.push(t); } else { one.push(t); nTime = (nTime + 1) % 2; return one.back(); } } } }
bool empty() { return nSize == 0; }
private: queue<T> one; queue<T> two; int nSize; int nTime; };
#define MAX 20
int main() { CStack<int> stack;
for (int i = 0; i < MAX; ++i) { stack.push(i); }
while (!stack.empty()) { printf("top: %d\n", stack.top()); stack.pop(); }