链栈的应用----匹配括号

1.使用函数一览

void DestroyLStack(LinkStNode * s);//销毁链栈
bool EmptyLStack(LinkStNode *s);//判空
bool Push(LinkStNode *s,ElemType e);//入栈操作
bool Pop(LinkStNode *s,ElemType e);//出栈操作
int GetLTop(LinkStNode *s,ElemType e);//取栈顶元素
bool MatchStack(LinkStNode *s,char exp[],int n);//匹配括号函数

2.头文件预编译

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
typedef char ElemType;

3.判空函数

bool EmptyLStack(LinkStNode *s){
    if(s -> next == NULL){
        printf("链栈为空\n");
        return false;
    } else{
        printf("链栈不为空\n");
        return true;
    }
}

4.入栈函数

bool Push(LinkStNode *s,ElemType e){
    LinkStNode *p;
    p = (LinkStNode*) malloc(sizeof(LinkStNode));
    p -> data = e;
    p -> next = s -> next;
    s -> next = p;
    printf("%c入栈成功\n",e);
    return true;
}

5.出栈函数

bool Pop(LinkStNode *s,ElemType e){
    if(s -> next == NULL){
        printf("栈为空\n");
        return false;
    }
    LinkStNode *p;
    p = s -> next;
    e = p -> data;
    s -> next = p -> next;
    free(p);
    printf("%c删除成功\n",e);
    return e;
}

6.取栈顶元素函数

int GetLTop(LinkStNode *s,ElemType e){
    if(s -> next == NULL){
        printf("栈为空\n");
        return false;
    }
    LinkStNode *p;
    p = s -> next;
    e = p -> data;
    printf("栈顶元素是%d\n",e);
    return e;
}

7.销毁函数

void DestroyLStack(LinkStNode * s) {
   LinkStNode *pre = s,*p = s -> next;
    while (p != NULL){
        free(pre);
        pre = p;
        p = pre -> next;
    }
    free(pre);
    printf("销毁成功\n");
}

8.匹配函数

bool MatchStack(LinkStNode *s,char exp[],int n){
    int i = 0; char e;
    bool match = true;
    while (i < n && match){
        if(exp[i] == '(') //左括号进栈,右括号判断栈顶元素,匹配则出栈
            Push(s,exp[i]);
        else if(exp[i] == ')'){
            if(EmptyLStack(s) == true)
            {
                int x = GetLTop(s,e);
                if(x != '(')
                    match = false;
                else
                    Pop(s,e);
            }
        } else{ //其他情况直接退出
            match = false;
        }
        i++;
    }
    if(EmptyLStack(s)) //链栈不为空,有括号未能匹配
        match = false;
    if(match)
        printf("匹配成功\n");
    else
        printf("匹配失败\n");
    DestroyLStack(s);
    return match;
}

9.主函数

int main(){
   LinkStNode *p;
   p = (LinkStNode * ) malloc(sizeof(LinkStNode));
   p -> next = NULL;
   char exp[10] = {'(','(',')',')','(','(','(',')',')',')'};
    MatchStack(p,exp,10);

}

 

对于括号匹配算法,栈的先进后出特性十分实用。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值