先来看说说c++里面的栈吧
c++里面封装了栈的标准库
使用标准库的栈和队列时,先包含相关的头文件
#include<stack>
#include<queue>
定义栈如下:
stack<int> stk;
定义队列如下:
queue<int> q;
栈提供了如下的操作
- s.empty() 如果栈为空返回true,否则返回false
- s.size() 返回栈中元素的个数
- s.pop() 删除栈顶元素但不返回其值
- s.top() 返回栈顶的元素,但不删除该元素
- s.push() 在栈顶压入新元素
队列提供了下面的操作
- q.empty() 如果队列为空返回true,否则返回false
- q.size() 返回队列中元素的个数
- q.pop() 删除队列首元素但不返回其值
- q.front() 返回队首元素的值,但不删除该元素
- q.push() 在队尾压入新元素
- q.back() 返回队列尾元素的值,但不删除该元素
栈的经典应用——括号匹配。(表达式匹配单独开其他文章吧)
输入左括号和大括号。
遇到左括号时压栈。
遇到右括号时,就要分情况了。
1.如果队列为空,匹配失败;
2.如果有队首元素,但是队首元素不是左括号,匹配失败;
3.如果是左括号,弹栈。
当所有用户输入完毕,判断栈的状态,若此时栈为空,则匹配成功,不为空则匹配失败。
#include <iostream>
#include <algorithm>
#include <string>
#include <vector>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <stack>
#include <map>
using namespace std;
int main(){
string a;
while(cin>>a){
stack <char> s;
for(int i=0;i<a.length();i++){
if(a[i]=='(')s.push(a[i]);(
if(a[i]==')')
{
cout<<a[i]<<endl;
if(s.empty()||s.top()!='('){
cout<<"不匹配"<<endl;
return 0;
}else if(s.top()=='('){s.pop();}
}
}
if(!s.empty()){cout<<"不匹配"<<endl;}
else {cout<<"匹配"<<endl;}
}
return 0;
}
先恋上一个表达式匹配把
点击打开链接
c语言封装一个栈
1、结构体定义
2、初始化
3、判断是否为空
4、取得栈顶值
5、入栈操作
6、出栈操作
7、打印栈的内容
1、结构体定义
2、初始化
3、判断是否为空
4、取得栈顶值
5、入栈操作
6、出栈操作
7、打印栈的内容