栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

括号匹配-栈

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

括号匹配-栈

题目

检查一段C语言代码的小括号( )、 中括号 [ ] 和大括号{ } 是否匹配。
,(),[],{}

思路
		将这段代码存入以字符串中,遍历字符串,分两种情况
		1.,遇到'/'并且栈顶元素不等于'/'时,将其入栈,初始情况栈为空,遇到‘*’同理,
			再次遇到这些符号时则栈顶元素出栈
		2.'()','[]','{}',这三种符号,只需要在遇到'(','[''{'时入栈,遇到')',']','}'时将栈顶元素出栈
		遍历完后判断栈是否为空,若为空则符号匹配,否则不匹配
代码
#include 
#include 
#include 
using namespace std;
const int maxn = 1010;
typedef struct node
{
	char data[maxn];
	int top;
} * link;
void Init(link stk)
{
	stk -> top = 0;
}
void Push_stk(link stk , int x)
{
	stk -> data[++stk -> top]= x;
}
void Pop_stk(link stk)
{
	stk -> top--;
}
int GetTop(link stk) 
{
	return stk -> data[stk -> top];
}
int Getsize(link stk)
{
	return stk -> top;
}
int Empty_stk(link stk)
{
	return !Getsize(stk);
}
int main()
{
	link stk = (link) malloc (sizeof(node));
	Init(stk);
	string s;
	cin >> s;
	int len = s.length();
	for(int i = 0 ; i < len ; i++)
	{
		if(s[i] != ',')
		{
			if(s[i] == '(')
				Push_stk(stk , s[i]);
			if(s[i] == ')')
				Pop_stk(stk);
			if(s[i] == '/' && GetTop(stk) != '/')
				Push_stk(stk , s[i]);
			if(s[i] == '*' && GetTop(stk) != '*')
				Push_stk(stk , s[i]);
			if(s[i] == '[')
				Push_stk(stk , s[i]);
			if(s[i] == '{')
				Push_stk(stk , s[i]);	
			if(s[i] == '}')
				Pop_stk(stk);
			if(s[i] == ']')
				Pop_stk(stk);
			if(s[i] == '*' && GetTop(stk) == '*')
				Pop_stk(stk);
			if(s[i] == '/' && GetTop(stk) == '/')
				Pop_stk(stk);
			if(s[i] == ')')
				Pop_stk(stk);
		}
	}
	if(!Empty_stk(stk))
		cout << "true";
	else
		cout << "false"; 
return 0;	
} 

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/396148.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号