/*
*仅对圆括号(),方括号<>,花括号{}进行校验;
*算法:创建一个空栈,读入字符至文件尾,如果是
*开放字符将其压栈,如果是闭合字符,此时栈空则
*报错,否则从栈中弹出一个字符,如果不是对应的开
*放字符,则报错,在文件尾栈非空报错。
*/
#include <stdio.h>
#include <stdlib.h>
struct Node;
typedef struct Node *PtrToNode;
typedef PtrToNode Stack;
typedef char ElementType;
struct Node
{
ElementType Element;
PtrToNode Next;
};
void Push(ElementType ch,Stack S)//插入在表头
{
Stack p;
p=(struct Node*)malloc(sizeof(struct Node));
p->Element=ch;
p->Next=S->Next;
S->Next=p;
}
int IsEmpty(Stack S)
{
return S->Next==NULL;
}
ElementType Top(Stack S)//表头为栈顶
{
if(!IsEmpty(S))
return S->Next->Element;
return 0;
}
void Pop(Stack S)
{
PtrToNode p=S->Next;
if(IsEmpty(S))
printf("Empty stack");
else
{
S->Next=p->Next;
free(p);
}
}
int relevantch(char ch1,char ch2)//两字符匹配则返回0
{
if((ch1=='('&&ch2==')')||(ch1==')'&&ch2=='('))
return 0;
else if((ch1=='<'&&ch2=='>')||(ch1=='>'&&ch2=='<'))
return 0;
else if((ch1=='{'&&ch2=='}')||(ch1=='}'&&ch2=='{'))
return 0;
else
return 1;
}
int main()
{
Stack S;//建立空栈S
S=(struct Node*)malloc(sizeof(struct Node));
S->Next=NULL;
char ch;
while(1)//使用while(ch!='\n')会带入一个回车字符。
{
scanf("%c",&ch);
if(ch=='\n')
break;
if(ch=='('||ch=='<'||ch=='{')
{
Push(ch,S);
}
else
{
if(IsEmpty(S))
printf("Error1");
else
{
if(relevantch(ch,Top(S)))
printf("Error2");
else
{
Pop(S);
}
}
}
}
return 0;
}
栈的应用—平衡符号
最新推荐文章于 2024-04-27 19:07:54 发布