#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define MAXSIZE 10
typedef struct
{
char data[MAXSIZE];
int top;
}SqStack;
//初始化栈
void InitStack(SqStack& S)
{
S.top = -1;
}
//判断栈是否为空
int EmptyStack(SqStack S)
{
if (S.top == -1)
return 0;
else
return 1;
}
//入栈
int PushStack(SqStack& S, char x)
{
if (S.top == MAXSIZE - 1)
return 0;
else
{
S.top++;
S.data[S.top] = x;
return 1;
}
}
//出栈
int PopStack(SqStack& S, char& x)
{
if (S.top == -1)
return 0;
else
{
x = S.data[S.top];
S.top--;
return 1;
}
}
int pipei(char str[], int length)
{
SqStack S;
InitStack(S);
for (int i = 0;i < length;i++)
{
if (str[i] == '(' || str[i] == '[' || str[i] == '{')
PushStack(S, str[i]);
else
{
if (EmptyStack(S))
return 0;
char topElem;
PopStack(S, topElem);//栈顶元素出栈
if (str[i] == ')' && topElem != '(')
return 0;
if (str[i] == ']' && topElem != '[')
return 0;
if (str[i] == '}' && topElem != '{')
return 0;
}
}
if (EmptyStack(S) == 0)//如果栈空,则匹配成功
return 1;
}
int main()
{
int l;
char a[10] = { 0 };
printf("请输入括号的总共个数:\n");
scanf_s("%d", &l);
printf("请输入要判断的括号序列");
for (int i = 0;i < l;i++)
{
scanf_s("%c", &a[i]);
}
pipei(a, l);
if (pipei(a, l) == 1)
printf("匹配正确\n");
else
printf("匹配失败\n");
return 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 '[':
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;
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");
}
}