介绍
栈是最基本的数据结构之一,特点是“先进后出”。例如乘坐电梯时,先进电梯的最后出来;一管泡腾片,最先放进的最后拿出。
常用操作
代码 | 解释 |
---|---|
stack | 定义栈,TYPE为数据模型,例如int, float, char等 |
s.puch(item); | 吧item放到栈顶 |
s.top(); | 返回栈顶的元素,但不会删除 |
s.pop(); | 删除栈顶的元素,但不会返回.在出栈时需要进行两步操作,即先top()获得栈顶元素,再pop()返回栈顶元素 |
s.size | 返回栈中元素的个数 |
s.empty | 检查栈是否为空,如果为空,返回true,否则返回false |
例题
#include <bits/stdc++.h>
using namespace std;
//输入:1 olleh !dlrow
//输出:hello world
int main()
{
int n;
char ch;
scanf("%d", &n); getchar();
while(n --){
stack<char>s;
while(true){
ch = getchar();//一次读入一个字符
if(ch == ' ' || ch == '\n' || ch == EOF){
while(!s.empty()){
printf("%c", s.top());//输出栈顶
s.pop();//清除栈顶
}
if(ch == '\n' || ch == EOF) break;
printf(" ");
}
else
s.push(ch);//入栈
}
printf("\n");
}
return 0;
}