我的第一次提交:
class MyStack { private: queue<int> int_queue; public: /** Initialize your data structure here. */ MyStack() { } /** Push element x onto stack. */ void push(int x) { int_queue.push(x); } /** Removes the element on top of the stack and returns that element. */ int pop() { for (int i=0; i<int_queue.size()-1; ++i){ int tmp = int_queue.front(); int_queue.pop(); int_queue.push(tmp); } int res = int_queue.front(); int_queue.pop(); return res; } /** Get the top element. */ int top() { int res = pop(); int_queue.push(res); return res; } /** Returns whether the stack is empty. */ bool empty() { return int_queue.empty(); } };缺点:push()操作简单,数据在元素中以队列形式存放,结果就是后面每次操作时都要循环处理数据,
查看别人代码,令人惊喜的是看到有人在push()操作时加一点工作量,让数据在队列中以栈的顺序存储好,接下来所有操作将变得简单。
新思路的第二次提交:
class MyStack { private: queue<int> int_queue; public: /** Initialize your data structure here. */ MyStack() { } /** Push element x onto stack. */ void push(int x) { int_queue.push(x); for (int i=0; i<int_queue.size()-1; ++i){ int_queue.push(int_queue.front()); int_queue.pop(); } } /** Removes the element on top of the stack and returns that element. */ int pop() { int res = int_queue.front(); int_queue.pop(); return res; } /** Get the top element. */ int top() { return int_queue.front(); } /** Returns whether the stack is empty. */ bool empty() { return int_queue.empty(); } };值得注意的是push()操作:
void push(int x) { nums.push(x); //将前面的size-1个元素放到后面去 for(int i = 0; i < nums.size() - 1; i++){ nums.push(nums.front()); nums.pop(); } }刚开始怀疑了好久,把前面元素整体挪到后面后导致第二次pop()出现错误,后来才猛然反应过来,前面元素push()时,也已经按这个规则完成反向排序,是我思考的慢了。
总结 C++ STL 的queue操作: queue<int> q; q.push()q.pop() 无返回值q.front() 返回队头元素q.back() 返回队尾元素q.size()q.empty() 本题是数据结构队列和栈的入门题、熟悉题。
转载于:https://www.cnblogs.com/ACStrive/p/11602440.html
相关资源:JAVA上百实例源码以及开源项目