- 对于栈的操作
- stIn.top():返回栈顶。
- stIn.pop():弹出栈顶。
- stIn.empty():返回栈是否为空,true为空。
- stIn.push():向栈中插入元素。
- 对于队列的操作
- push(x) : 将一个元素放入队列的尾部。
- pop() : 从队列首部移除元素。
- peek() : 返回队列首部的元素。
- empty() : 返回队列是否为空。
- 两个栈实现队列
- 一个负责入栈stIn,后进先出。
- 一个负责接受栈stIn出栈的数据,先进后出。
- 通过栈后进先出,先进后出实现队列的先进先出。
class MyQueue {
public:
stack<int> stIn;
stack<int> stOut;
MyQueue() {
}
void push(int x) {
stIn.push(x);
}
int pop() {
if(stOut.empty()){
while(!stIn.empty()){
stOut.push(stIn.top());
stIn.pop();
}
}
int tmp = stOut.top();
stOut.pop();
return tmp;
}
int peek() {
if(stOut.empty()){
while(!stIn.empty()){
stOut.push(stIn.top());
stIn.pop();
}
}
int tmp = stOut.top();
return tmp;
}
bool empty() {
if(stIn.empty() && stOut.empty()) return true;
return false;
}
};
- 两个队列:
- 一个队列实现保存元素;
- 一个队列始终为空,接受另一个队列的n-1个元素,如果是pop,返回另一个队列的最后一个元素并删除,如果是top,返回另一个队列的最后一个元素并插入到这个队列中。用队列的先进先出实现栈的先进后出。
class MyStack {
public:
queue<int> qIn1;
queue<int> qIn2;
MyStack() {
}
void push(int x) {
qIn1.push(x);
}
int pop() {
if(qIn1.empty() && !qIn2.empty()){
int tmp = qIn2.front();
qIn2.pop();
while(!qIn2.empty()){
qIn1.push(tmp);
tmp = qIn2.front();
qIn2.pop();
}
return tmp;
}
else {
int tmp = qIn1.front();
qIn1.pop();
while(!qIn1.empty()){
qIn2.push(tmp);
tmp = qIn1.front();
qIn1.pop();
}
return tmp;
}
}
int top() {
if(qIn1.empty() && !qIn2.empty()){
int tmp = 0;
while(!qIn2.empty()){
tmp = qIn2.front();
qIn2.pop();
qIn1.push(tmp);
}
return tmp;
}
else {
int tmp = 0;
while(!qIn1.empty()){
tmp = qIn1.front();
qIn1.pop();
qIn2.push(tmp);
}
return tmp;
}
}
bool empty() {
if(qIn1.empty() && qIn2.empty()) return true;
return false;
}
};