标签:The init ant code amp 剑指offer 编程 输入 return
请用栈实现一个队列,支持如下四种操作:
注意:
push to top
,peek/pop from top
, size
和 is empty
;
pop
或者peek
等操作;MyQueue queue = new MyQueue();
queue.push(1);
queue.push(2);
queue.peek(); // returns 1
queue.pop(); // returns 1
queue.empty(); // returns false
class MyQueue { public: /** Initialize your data structure here. */ stack<int> stack1,stack2; MyQueue() { } /** Push element x to the back of queue. */ void push(int x) { stack1.push(x); } void copy(stack<int> &a, stack<int>& b){ while(a.size()){ b.push(a.top()); a.pop(); } } /** Removes the element from in front of queue and returns that element. */ int pop() { copy(stack1, stack2); int result = stack2.top(); stack2.pop(); copy(stack2,stack1); return result; } /** Get the front element. */ int peek() { copy(stack1, stack2); int result = stack2.top(); copy(stack2,stack1); return result; } /** Returns whether the queue is empty. */ bool empty() { return stack1.empty(); } }; /** * Your MyQueue object will be instantiated and called as such: * MyQueue obj = MyQueue(); * obj.push(x); * int param_2 = obj.pop(); * int param_3 = obj.peek(); * bool param_4 = obj.empty(); */
标签:The init ant code amp 剑指offer 编程 输入 return
原文地址:https://www.cnblogs.com/tingweichen/p/10624770.html