括号匹配用数据结构栈解决c/c++

括号匹配{}或者是{[()]}这类的是一个合法的括号序列用数据结构的栈来解决

#include
#include
#include
using namespace std;
#define MAXSIZE 100
int k;
char ch[1000];
enum Status{
	OK=1,
	ERROR=0,
	OVERFLOW=-1
};
struct SqStack{
	//定义一个栈 
	char *base;
	char *top;
	int StackSize;
	Status Init(SqStack &S){
		//对栈进行初始化 
		S.base=new char[MAXSIZE];
		S.top=S.base;
		S.StackSize=MAXSIZE;
		return OK;
	}
	Status push(SqStack &S,char e){
		//压栈 
		if((S.top-S.base)>=MAXSIZE)
			return OVERFLOW;
		*S.top++=e;
		S.StackSize--;
		return OK;
	}
	Status pop(SqStack &S,char &e){
		//出栈 
		if(S.top==S.base)
			return ERROR;
		e=*--S.top;
		S.StackSize++;
		return OK;
	}
	bool empty(SqStack S){
		//判断栈是否为空 
		if(S.StackSize==MAXSIZE)
			return true;
		return false;
	}
};
bool Solve(){
	SqStack S;
	S.Init(S);
	for(int i=1;i<=k;i++){
		//如果为左括号就入栈,右括号就出栈 
		if(ch[i]=='('||ch[i]=='{'||ch[i]=='[')
			S.push(S,ch[i]);
		if(ch[i]==')'){
			char e;
			S.pop(S,e);
			if(e!='(')
				return false;
		}
		if(ch[i]==']'){
			char e;
			S.pop(S,e);
			if(e!='[')
				return false;
		}
		if(ch[i]=='}'){
			char e;
			S.pop(S,e);
			if(e!='{')
				return false;
		}
	}
	if(S.empty(S))
		return true;
	return false;
}
int main()
{
	char c;
	printf("请输入一连串括号用#结尾:");
	while((c=getchar())!=EOF){
		if(c=='('||c=='['||c=='{'||c==')'||c==']'||c=='}')
			ch[++k]=c; 
		if(c=='#')
			break;
	}
	printf("输入的括号序列为: ");
	for(int i=1;i<=k;i++)
		cout<<ch[i];
	cout<<endl;
	if(Solve())
		printf("这是一个匹配的括号序列!!!\n");
	else printf("这不是一个匹配的括号序列!!!\n");
	return 0;
}

你可能感兴趣的:(数据结构大作业,c语言,数据结构,链表,算法,c++)