数据结构--括号匹配检验

//本程序用于学习数据结构中的顺序栈
//调试环境 C-Free 5.0 
#include<stdio.h>
#include<malloc.h>
#define MAXSIZE 100
typedef struct
{
	int *base;  //栈底指针 
	int *top;   //栈顶指针 
	int stacksize;
}SqStack;

void InitStack(SqStack*s)
{
	s->base = (int *)malloc(MAXSIZE*sizeof(int));//分配内存空间  100*sizeof(int) 
	if (!s->base)    
	{
		return;   //栈空(分配失败) 
	}
	s->top = s->base;     
	s->stacksize = MAXSIZE; 
}
void push(SqStack *s, char x)  //元素进栈 
{
	if (s->top-s->base==s->stacksize)   //栈满 
	{
		return;
	}
	*s->top++ = x;  
}
char GetTop(SqStack *s)   //取栈栈顶元素 
{
	if (s->top != s->base)
	{
		return*(s->top-1);      
	}

}
char pop(SqStack *s)    //元素出栈 
{
	if (s->top == s->base)
	{
		return' '; 
	}
	char e;
	e = *--s->top;
	return e;
}
int Maching()
{
	SqStack ss;     //声明一个结构体 
	SqStack *s = &ss;  //指向结构体的指针 
	InitStack(s);   //初始化栈 
	int flag = 1;
	printf("请输入符号");
	char ch = getchar();
	while (ch != '#'&&flag)
	{
		switch(ch)
		{
			//char aa;
			//char bb;
			case '[':
			case '(':
					push(s, ch);  //压入栈 
					break;
				case ')':
				    //aa=GetTop(s);
					if (!(s->top == s->base) && GetTop(s) == '(')
					{
						pop(s);  //出栈 
					}
					else
					{
						flag = 0;
					}
					break;
				case ']':
				    //bb=GetTop(s);
					if (!(s->top == s->base) &&GetTop(s) == '[')
					{
						pop(s);  //出栈 

					}
					else
					{
						flag = 0;
					}
					break;
		}
		ch = getchar();	
	}
	if (s->top == s->base)
		{
			return 1;                    
		}
		else
		{
			return 0;
		}
}

void main()
{
	int n; 
	n=Maching();
	if(n)
	{
		printf("匹配成功\n"); 
	}
	else
	{
		printf("匹配失败\n");
	}
}

    原文作者:括号匹配问题
    原文地址: https://blog.csdn.net/weixin_40258914/article/details/78583989
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞