#include <stdio.h>
#include <malloc.h>
typedef char DataType;
typedef struct stacknode
{
DataType data;
struct stacknode *next;
} LinkStack;
LinkStack *InitStack()
{
LinkStack *S;
S = NULL;
return S;
}
int EmptyStack(LinkStack *S)
{
if (S == NULL)
return 1;
else
return 0;
}
LinkStack *Pop(LinkStack *S, DataType *x)
{
LinkStack *p;
if (EmptyStack(S))
{
printf("\t 栈空,不能出栈!");
return NULL;
}
else
{
*x = S->data;
p = S;
S = S->next;
free(p);
return S;
}
}
LinkStack *Push(LinkStack *S, DataType x)
{
LinkStack *p;
p = (LinkStack *)malloc(sizeof(LinkStack));
p->data = x;
p->next = S;
S = p;
return S;
}
int GetTop(LinkStack *S, DataType *x)
{
if (EmptyStack(S))
{
printf("\t 栈空!");
return 0;
}
else
{
*x = S->data;
return 1;
}
}
void ShowStack(LinkStack *S)
{
LinkStack *p = S;
if (EmptyStack(S))
{
printf("\t 栈空!");
}
else
{
printf("从栈顶元素起栈中各元素为:");
while (p != NULL)
{
printf("%2d", p->data);
p = p->next;
}
}
}
void ParenMatch(LinkStack *S, DataType *y)
{
char *paren = y;
char x;
for (int i = 0; paren[i] != '\0'; i++)
{
switch (paren[i])
{
case '(':
case '[':
case '{':
S = Push(S, paren[i]);
break;
case ')':
S = Pop(S, &x);
if (x != '(')
{
printf("括号不匹配");
return;
}
break;
case ']':
S = Pop(S, &x);
if (x != '[')
{
printf("括号不匹配");
return;
}
break;
case '}':
S = Pop(S, &x);
if (x != '{')
{
printf("括号不匹配");
return;
}
break;
default:
break;
}
}
if (EmptyStack(S))
printf("所有括号都匹配");
else
printf("括号不匹配");
}
int main()
{
int x;
LinkStack *Stack;
Stack = InitStack(Stack);
char *y;
char *n;
y = "{[(1+2)-3]*4}";
n = "{[(1+2-3]*4}";
ParenMatch(Stack, n);
return 0;
}
C语言用栈的思想判断括号是否匹配
最新推荐文章于 2022-08-18 23:12:07 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)