栈的应用—平衡符号

/*
*仅对圆括号(),方括号<>,花括号{}进行校验;
*算法:创建一个空栈,读入字符至文件尾,如果是
*开放字符将其压栈,如果是闭合字符,此时栈空则
*报错,否则从栈中弹出一个字符,如果不是对应的开
*放字符,则报错,在文件尾栈非空报错。
*/
#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;
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值