232.用栈实现队列
232. Implement Queue using Stacks
C++:
class MyQueue {
public:
stack<int> stackIn;
stack<int> stackOut;
MyQueue() {
/*stack<int> stackIn=new stack<int>;
stack<int> stack Out=new stack<int>;*/
}
void push(int x) {
stackIn.push(x);
}
int pop() {
if(stackOut.empty()){
while(!stackIn.empty()){
stackOut.push(stackIn.top());
stackIn.pop();
}
}
int result=stackOut.top();
stackOut.pop();
return result;
}
int peek() {
int res = this->pop(); // 直接使用已有的pop函数
stackOut.push(res); // 因为pop函数弹出了元素res,所以再添加回去
return res;
}
bool empty() {
return stackIn.empty() && stackOut.empty();
}
};
C#:
public class MyQueue {
Stack<int> InStack;
Stack<int> OutStack;
public MyQueue() {
InStack=new Stack<int>();
OutStack=new Stack<int>();
}
public void Push(int x) {
InStack.Push(x);
}
public int Pop() {
if(OutStack.Count==0){
while(InStack.Count!=0){
OutStack.Push(InStack.Pop());
}
}
return OutStack.Pop();
}
public int Peek() {
if(OutStack.Count==0){
while(InStack.Count!=0){
OutStack.Push(InStack.Pop());
}
}
return OutStack.Peek();
}
public bool Empty() {
return InStack.Count == 0 && OutStack.Count == 0;
}
}
225. 用队列实现栈
225. Implement Stack using Queues
C++:
class MyStack {
public:
queue<int> que1;
//queue<int> que2; // 辅助队列,用来备份
MyStack() {
}
void push(int x) {
que1.push(x);
}
int pop() {
int size=que1.size();
size--;
while(size--){
que1.push(que1.front());
que1.pop();
}
int res=que1.front();
que1.pop();
return res;
}
int top() {
return que1.back();
}
bool empty() {
return que1.empty();
}
};
C#:
双队列,每次当Q2有数压入,从Q1弹出数再压入Q2实现入栈
public class MyStack {
Queue<int> queue1;
Queue<int> queue2;//存储
public MyStack() {
queue1 = new Queue<int>();
queue2 = new Queue<int>();
}
public void Push(int x) {
queue2.Enqueue(x);
while(queue1.Count!=0){
queue2.Enqueue(queue1.Dequeue());
}
Queue<int> queueTemp;
queueTemp=queue1;
queue1=queue2;
queue2=queueTemp;
}
public int Pop() {
return queue1.Count > 0 ? queue1.Dequeue() : -1;
}
public int Top() {
return queue1.Count > 0 ? queue1.Peek() : -1;
}
public bool Empty() {
return queue1.Count == 0;
}
}