本文共 1591 字,大约阅读时间需要 5 分钟。
能不用指针就不用指针;
class Stack {public: // Push element x onto stack. void push(int x) { queue & q = queueToPush(); q.push(x); } // Removes the element on top of the stack. void pop() { queue & from = queueToPush(); queue & to = emptyQueue(); transport(from, to); from.pop(); } // Get the top element. int top() { queue & from = queueToPush(); queue & to = emptyQueue(); transport(from, to); int ret = from.front(); to.push(ret); from.pop(); return ret; } // Return whether the stack is empty. bool empty() { return q1.empty() && q2.empty(); } queue & queueToPush(){ return q1.empty() ? q2 : q1; } queue & emptyQueue(){ return q1.empty() ? q1 : q2; } void transport(queue &from, queue &to){ while (from.size() > 1){ int temp = from.front(); to.push(temp); from.pop(); } }private: queue q1; queue q2;};
转载地址:http://zjpbb.baihongyu.com/