c++标准库已经为我们准备好这种结构。。stack::pop完成的仅仅是移除最顶端数据,如果要访问要使用stack::top函数(这个操作通常也称为peek)。
#include<cstdio> #include<stack> using namespace std; int main() { stack <int> s; //声明储存int型的栈。 s.push(1); //入栈操作 s.push(2); s.push(3); printf("%d\n",s.top()); s.pop(); //出栈操作 printf("%d\n",s.top()); s.pop(); printf("%d\n",s.top()); return 0; }
队列是用queue::front用来访问最低端数据的函数。
#include<cstdio> #include<queue> using namespace std; int main() { queue <int> que; que.push(1); que.push(2); que.push(3); printf("%d\n",que.front()); que.pop(); printf("%d\n",que.front()); que.pop(); printf("%d\n",que.front()); return 0; }