栈——数据结构


顺序栈,链栈及其应用——括号匹配算法


#include<stdio.h>
#include<stdlib.h>
#define maxn 100

typedef struct  //顺序栈;
{
    char elem[maxn];
    int top;
}SeqStack;

void InitStack(SeqStack *S)
{
    S->top=-1;
}

void Push(SeqStack *S,char x)
{
    if(S->top==maxn-1) return;
    S->top++;
    S->elem[S->top]=x;
}

void Pop(SeqStack *S,char *x)
{
    if(S->top==-1) return;
    else{
        *x=S->elem[S->top--];
    }
}

void GetTop(SeqStack *S,char *x)
{
    if(S->top==-1) return;
    else{
        *x=S->elem[S->top];
    }
}

typedef struct node  //链栈;
{
    char data;
    struct node *next;
}LinkStackNode,*LinkStack;

void InitLink(LinkStack L)
{
    L=(LinkStackNode*)malloc(sizeof(LinkStackNode));
    L->next=NULL;
}

void push(LinkStack top,char x)
{
    LinkStackNode *temp;
    temp=(LinkStackNode*)malloc(sizeof(LinkStackNode));
    if(temp==NULL) return;
    temp->data=x;
    temp->next=top->next;
    top->next=temp;
}

void pop(LinkStack top,char *x)
{
    LinkStackNode *temp;
    temp=top->next;
    if(temp==NULL) return;
    top->next=temp->next;
    *x=temp->data;
    free(temp);
}

bool Match(char x,char y)
{
    if((x=='('&&y==')')||(x=='['&&y==']')||(x=='{'&&y=='}')) return true;
    else return false;
}

void BrachetMach(char *str)  //括号匹配算法;
{
    SeqStack S;
    int i;
    char ch;
    InitStack(&S);
    for(int i=0;str[i]!='\0';i++){
        switch(str[i]){
            case'(':
            case'[':
            case'{':
                Push(&S,str[i]);
                break;
            case')':
            case']':
            case'}':
                if(S.top==-1){
                    printf("\n右括号多余!");
                    return;
                }
                else{
                    GetTop(&S,&ch);
                    if(Match(ch,str[i])) Pop(&S,&ch);
                    else{
                        printf("\n对应左右括号不匹配!");
                        return;
                    }
                }
        }
    }
    if(S.top==-1) printf("\n括号匹配");
    else printf("\n左括号多余!");
}

int main()
{
    SeqStack s;
    LinkStackNode l;
    char c;
    char str[100];
    InitStack(&s);
    InitLink(&l);
    c='a';
    for(int i=0;i<10;i++){
        Push(&s,c);
        c++;
    }
    for(int i=0;i<10;i++){
        Pop(&s,&c);
        printf("%c ",c);
    }
    printf("\n");
    c='A';
    for(int i=0;i<10;i++){
        push(&l,c);
        c++;
    }
    for(int i=0;i<10;i++){
        pop(&l,&c);
        printf("%c ",c);
    }
    printf("\n");
    scanf("%s",str);
    BrachetMach(str);
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值