栈在括号匹配中的应用

//栈在括号匹配中的应用 
#include<stdio.h>
#include<stdlib.h>
typedef int Position;
typedef char ElementType; 

struct SNode{
	ElementType *Data;
	Position Top;
	int MaxSize;
}; 
typedef struct SNode *Stack;
Stack CreatStack(int MaxSize);
bool IsFull(Stack S);
bool Push(Stack S,ElementType X);
bool IsEmpty(Stack S);
ElementType Pop(Stack S);
bool bracketCheck(char str[],int length)
{
	Stack S=CreatStack(10);
	for(int i=0;i<length;i++){
		if(str[i]=='('||str[i]=='['||str[i]=='{')
			Push(S,str[i]);
		else{
			if(IsEmpty(S))
				return false;
			char topElem=Pop(S);
//			if(str[i]==')'&&topElem!='(')
//				return false;
//			if(str[i]==']'&&topElem!='[')
//				return false;
//			if(str[i]=='}'&&topElem!='{')//str[i]等于这三种,再把每种的false表示出来 
//				return false;
			if(!((str[i]==')'&&topElem=='(')||(str[i]==']'&&topElem=='[')||(str[i]=='}'&&topElem=='{')))
				return false;
		}	
	}
	return IsEmpty(S); 
}
int main()
{
	char str[]="({})";
	if(bracketCheck(str,4))
		printf("匹配成功\n"); 
	else
		printf("匹配失败\n");
	return 0;
}
typedef struct SNode *Stack;
Stack CreatStack(int MaxSize)
{
	Stack S=(Stack)malloc(sizeof(struct SNode));
	S->Data=(ElementType*)malloc(sizeof(ElementType)*MaxSize);
	S->Top=-1;
	S->MaxSize=MaxSize;
}
bool IsFull(Stack S)
{
	return (S->Top==S->MaxSize-1);
}
bool Push(Stack S,ElementType X)
{
	if(IsFull(S)){
		printf("堆栈满\n");
		return false;
	}
	else{
		S->Data[++S->Top]=X;
		return true;
	}
}
bool IsEmpty(Stack S)
{
	return (S->Top==-1);
}
ElementType Pop(Stack S)
{
	if(IsEmpty(S)){
		printf("堆栈空/n");
		return false;
	}
	else
	return S->Data[S->Top--]; 
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值