mirror of
https://github.com/ShusenTang/LeetCode.git
synced 2024-09-02 14:20:01 +00:00
update 232
This commit is contained in:
parent
5f8da300d2
commit
338ea9cf7c
@ -1,45 +1,31 @@
|
||||
# [232. Implement Queue using Stacks](https://leetcode.com/problems/implement-queue-using-stacks/description/)
|
||||
# 思路
|
||||
用栈实现队列。
|
||||
设置两个栈stk1和stk2,stk1中的元素是按照正常入栈顺序排的,stk2则是逆序,且同一时刻stk1和stk2至少一个为空。
|
||||
若stk1不空,对队列入队的话直接对stk1入栈即可,否则要将stk2中所有元素pop到stk1中后再对stk1入栈。
|
||||
若stk2不空,对队列出队的话直接对stk2出栈即可,否则要将stk1中所有元素pop到stk2中后再对stk2出栈。
|
||||
用两个栈实现队列。
|
||||
设置两个栈stk1和stk2,基本思路是stk1用作input(入队), stk2用作output(出队)。
|
||||
|
||||
入队:无脑入栈stk1即可;
|
||||
出队:若stk2为空,那么先将stk1所有元素依次pop然后push进stk2,此时stk2栈顶元素就是最开始入队的元素,所以pop即可。
|
||||
|
||||
# C++
|
||||
``` C++
|
||||
class MyQueue {
|
||||
private:
|
||||
stack<int>stk1;
|
||||
stack<int>stk2;
|
||||
stack<int>stk1; // input
|
||||
stack<int>stk2; // output
|
||||
public:
|
||||
/** Initialize your data structure here. */
|
||||
MyQueue() {
|
||||
MyQueue() {}
|
||||
|
||||
}
|
||||
/** Push element x to the back of queue. */
|
||||
void push(int x) {
|
||||
if(stk1.empty()){
|
||||
int tmp;
|
||||
while(!stk2.empty()){
|
||||
tmp = stk2.top();
|
||||
stk2.pop();
|
||||
stk1.push(tmp);
|
||||
}
|
||||
}
|
||||
stk1.push(x);
|
||||
}
|
||||
|
||||
/** Removes the element from in front of queue and returns that element. */
|
||||
int pop() {
|
||||
int tmp;
|
||||
if(stk2.empty()){
|
||||
while(!stk1.empty()){
|
||||
tmp = stk1.top();
|
||||
stk1.pop();
|
||||
stk2.push(tmp);
|
||||
}
|
||||
}
|
||||
tmp = stk2.top();
|
||||
int res = peek();
|
||||
stk2.pop();
|
||||
return tmp;
|
||||
return res;
|
||||
}
|
||||
|
||||
/** Get the front element. */
|
||||
|
Loading…
Reference in New Issue
Block a user