首页 > 学院 > 开发设计 > 正文

双栈队列练习

2019-11-08 02:22:13
字体:
来源:转载
供稿:网友

链接:https://www.nowcoder.com/courses/1/4/4 来源:牛客网

编写一个类,只能用两个栈结构实现队列,支持队列的基本操作(push,pop)。 给定一个操作序列ope及它的长度n,其中元素为正数代表push操作,为0代表pop操作,保证操作序列合法且一定含pop操作,请返回pop的结果序列。 测试样例: [1,2,3,0,4,0],6 返回:[1,2]

这个题目需要注意返回的是pop的结果序列,也就是返回整个操作序列pop出的元素。 另外双栈队列在取出front元素和pop时都可能需要搬运元素。这个需要注意。

class twostackqueue {public: twostackqueue() {} void push(int a) { stack_push.push(a); } void pop() { if(!stack_pop.empty()) stack_pop.pop(); else if(!stack_push.empty()) { while(!stack_push.empty()){ stack_pop.push(stack_push.top()); stack_push.pop(); } stack_pop.pop(); } else return; } int front() { if(!stack_pop.empty()) return stack_pop.top(); else if(!stack_push.empty()) { while(!stack_push.empty()){ stack_pop.push(stack_push.top()); stack_push.pop(); } return stack_pop.top(); } return -1; }PRivate: stack<int> stack_push; stack<int> stack_pop;};class TwoStack {public: vector<int> twoStack(vector<int> ope, int n) { vector<int> res; twostackqueue que; for(int i=0;i!=n;++i) { if(ope[i]>0){ que.push(ope[i]); } else { res.push_back(que.front()); que.pop(); } } return res; }};
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表