栈和队列相关知识:
一般队列支持的所有操作(push、pop、peek、empty):
void push(int x) 将元素 x 推到队列的末尾
int pop() 从队列的开头移除并返回元素
int peek() 返回队列开头的元素
boolean empty() 如果队列为空,返回 true ;否则,返回 false。
一般栈支持的操作
push to top, peek/pop from top, size, 和 is empty
栈的相关知识
栈提供push 和 pop 等等接口,所有元素必须符合先进后出规则,所以栈不提供走访功能,也不提供迭代器(iterator)。 不像是set 或者map 提供迭代器iterator来遍历所有元素。
栈是以底层容器完成其所有的工作,对外提供统一的接口,底层容器是可插拔的(也就是说我们可以控制使用哪种容器来实现栈的功能)。
所以STL中栈往往不被归类为容器,而被归类为container adapter(容器适配器)。
栈的内部结构,栈的底层实现可以是vector,deque,list 都是可以的, 主要就是数组和链表的底层实现。
例如:指定vector为栈的底层实现,初始化语句如下:
std::stack<int, std::vector<int> > third; // 使用vector为底层容器的栈
队列的相关知识
队列中先进先出的数据结构,同样不允许有遍历行为,不提供迭代器, SGI STL中队列一样是以deque为缺省情况下的底部结构。
也可以指定list 为起底层实现,初始化queue的语句如下:
std::queue<int, std::list<int>> third; // 定义以list为底层容器的队列
所以STL 队列也不被归类为容器,而被归类为container adapter( 容器适配器)。
232.用栈实现队列
这题主要考察的是栈和队列的基础知识
代码实现
class MyQueue {
public:
stack<int> stIn;
stack<int> stOut;
MyQueue(){
}
//push 将元素 x 推到队列的末尾
void push(int x){
stIn.push(x);
}
//pop 从队列的开头移除并返回元素
int pop(){
if(stOut.empty())
{
while(!stIn.empty()){
stOut.push(stIn.top());
stIn.pop();
}
}
int result = stOut.top();
stOut.pop();//移出队列开头元素
return result;//并返回移出的元素
}
//peek 返回队列开头的元素
int peek(){
int res = this->pop(); //直接调用pop函数
stOut.push(res); //把pop函数中弹出的res再push进去
return res;//返回res
}
//empty
bool empty(){
return stIn.empty() && stOut.empty();
}
};
225. 用队列实现栈
class MyStack {
public:
queue<int> queue1;
queue<int> queue2;
MyStack(){
}
//push
void push(int x){
queue1.push(x);
}
//pop
int pop(){
int count = queue1.size();
count--;
while(count--)
{
queue2.push(queue1.front());//把最后一个元素之前的元素push到queue2
queue1.pop();//把queue1中的元素删除
}
int result = queue1.front();
queue1.pop();
queue1 = queue2;//把queue2中的元素重新放入queue1
while(!queue2.empty())
{
queue2.pop();
}
return result;
}
//top
int top(){
int res = this->pop();
queue1.push(res);
return res;
}
//empty
bool empty(){
return queue1.empty() && queue2.empty();
}
};