[LeetCode 232]C++实现用栈实现队列
请你仅使用两个栈实现先入先出队列。队列应当支持一般队列的支持的所有操作(push、pop、peek、empty):
实现 MyQueue 类:
void push(int x) 将元素 x 推到队列的末尾
int pop() 从队列的开头移除并返回元素
int peek() 返回队列开头的元素
boolean empty() 如果队列为空,返回 true ;否则,返回 false
说明:
你只能使用标准的栈操作 —— 也就是只有 push to top, peek/pop from top, size, 和 is empty 操作是合法的。
你所使用的语言也许不支持栈。你可以使用 list 或者 deque(双端队列)来模拟一个栈,只要是标准的栈操作即可。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/implement-queue-using-stacks
方法1、利用两个栈模拟队列
例:
data:1 2 3 4
temp:4 3 2 1
after insert val: 4 3 2 1 val
data:val 1 2 3 4
pop(): 4 //后进后出
class MyQueue {
stack<int>data_stack;
stack<int>temp_stack;
public:
/** Initialize your data structure here. */
MyQueue() {
}
/** Push element x to the back of queue. */
void push(int x) {
while(!data_stack.empty()){
temp_stack.push(data_stack.top());
data_stack.pop();
}
temp_stack.push(x);
while(!temp_stack.empty()){
data_stack.push(temp_stack.top());
temp_stack.pop();
}
}
/** Removes the element from in front of queue and returns that element. */
int pop() {
int data=data_stack.top();
data_stack.pop();
return data;
}
/** Get the front element. */
int peek() {
return data_stack.top();
}
/** Returns whether the queue is empty. */
bool empty() {
return data_stack.empty();
}
};
方法2、两个栈模拟U型队列
class MyQueue {
public:
stack<int>temp_stack;//输出栈
stack<int>data_stack;//data栈
/** Initialize your data structure here. */
MyQueue() {
}
/** Push element x to the back of queue. */
void push(int x) {
data_stack.push(x);
}
/** Removes the element from in front of queue and returns that element. */
int pop() {
if(temp_stack.empty()){
while(!data_stack.empty()){
temp_stack.push(data_stack.top());
data_stack.pop();
}
}
int val=temp_stack.top();
temp_stack.pop();
return val;
}
/** Get the front element. */
int peek() {
if(temp_stack.empty()){
while(!data_stack.empty()){
temp_stack.push(data_stack.top());
data_stack.pop();
}
}
return temp_stack.top();
}
/** Returns whether the queue is empty. */
bool empty() {
return data_stack.empty()&&temp_stack.empty();
}
};