理论基础
1.我们常用的SGI STL栈,如果没有指定底层实现的话,默认是以deque为缺省情况下栈的底层结构。
2.STL 队列、栈也不被归类为容器,而被归类为container adapter( 容器适配器)。
3.栈、队列不提供走访功能,也不提供迭代器(iterator)
4.queue
-
push(elem);
//往队尾添加元素 -
pop();
//从队头移除第一个元素 -
back();
//返回最后一个元素 -
front();
//返回第一个元素
5.stack
-
push(elem);
//向栈顶添加元素 -
pop();
//从栈顶移除第一个元素 -
top();
//返回栈顶元素
232.用栈实现队列
class MyQueue {
public:
stack<int> stIn;
stack<int> stOut;
/** Initialize your data structure here. */
MyQueue() {
}
/** Push element x to the back of queue. */
void push(int x) {
stIn.push(x);
}
/** 从队列的开头移除并返回元素Removes the element from in front of queue and returns that element. */
int pop() {
// 只有当stOut为空的时候,再从stIn里导入数据(导入stIn全部数据)
if (stOut.empty()) {
// 从stIn导入数据直到stIn为空
while(!stIn.empty()) {
stOut.push(stIn.top());//将in的top存入out中
stIn.pop(); //将已经存入out中的in的top删除
}
}
//读取out的top为result,并将它出栈
int result = stOut.top();
stOut.pop();
return result;
}
/** Get the front element. */
int peek() {
int res = this->pop(); // 直接使用已有的pop函数
stOut.push(res); // 因为pop函数弹出了元素res,所以再添加回去
return res;
}
/** Returns whether the queue is empty. */
bool empty() {
return stIn.empty() && stOut.empty();
}
};
225. 用队列实现栈理论基础
class MyStack {
public:
queue<int> que;
/** Initialize your data structure here. */
MyStack() {
}
/** Push element x onto stack. */
void push(int x) {
que.push(x);
}
/** 移除并返回栈顶元素。Removes the element on top of the stack and returns that element. */
int pop() {
int size = que.size();
size--;
while (size--) { // 将队列头部的元素(除了最后一个元素外) 重新添加到队列尾部
que.push(que.front());
que.pop();
}
int result = que.front(); // 此时弹出的元素顺序就是栈的顺序了
que.pop();
return result;
}
/** Get the top element. */
int top() {
return que.back();
}
/** Returns whether the stack is empty. */
bool empty() {
return que.empty();
}
};