第六周项目~括号匹配

来源:互联网 发布:java邮件发送图片 编辑:程序博客网 时间:2024/06/03 20:55

listack.h:

#ifndef LISTACK_H_INCLUDED#define LISTACK_H_INCLUDEDtypedef char ElemType;typedef struct linknode{    ElemType data;              //数据域    struct linknode *next;      //指针域} LiStack;                      //链栈类型定义void InitStack(LiStack *&s);  //初始化栈void DestroyStack(LiStack *&s);  //销毁栈int StackLength(LiStack *s);  //返回栈长度bool StackEmpty(LiStack *s);  //判断栈是否为空void Push(LiStack *&s,ElemType e);  //入栈bool Pop(LiStack *&s,ElemType &e);  //出栈bool GetTop(LiStack *s,ElemType &e);  //取栈顶元素void DispStack(LiStack *s);  //输出栈中元素#endif // LISTACK_H_INCLUDED


listack.cpp:

#include <stdio.h>#include <malloc.h>#include "listack.h"void InitStack(LiStack *&s)  //初始化栈{    s=(LiStack *)malloc(sizeof(LiStack));    s->next=NULL;}void DestroyStack(LiStack *&s)  //销毁栈{    LiStack *p=s->next;    while (p!=NULL)    {        free(s);        s=p;        p=p->next;    }    free(s);    //s指向尾结点,释放其空间}int StackLength(LiStack *s)  //返回栈长度{    int i=0;    LiStack *p;    p=s->next;    while (p!=NULL)    {        i++;        p=p->next;    }    return(i);}bool StackEmpty(LiStack *s)  //判断栈是否为空{    return(s->next==NULL);}void Push(LiStack *&s,ElemType e)  //入栈{    LiStack *p;    p=(LiStack *)malloc(sizeof(LiStack));    p->data=e;              //新建元素e对应的节点*p    p->next=s->next;        //插入*p节点作为开始节点    s->next=p;}bool Pop(LiStack *&s,ElemType &e)  //出栈{    LiStack *p;    if (s->next==NULL)      //栈空的情况        return false;    p=s->next;              //p指向开始节点    e=p->data;    s->next=p->next;        //删除*p节点    free(p);                //释放*p节点    return true;}bool GetTop(LiStack *s,ElemType &e)  //取栈顶元素{    if (s->next==NULL)      //栈空的情况        return false;    e=s->next->data;    return true;}void DispStack(LiStack *s)  //输出栈中元素{    LiStack *p=s->next;    while (p!=NULL)    {        printf("%c ",p->data);        p=p->next;    }    printf("\n");}


改变main.cpp:

#include "sqstack.h"#include<iostream>bool isMatch(char *st){    int d=1, i;    char c;    SqStack *s;    InitStack(s);    for(i=0; st[i]!='\0'&&d; i++)    {        switch(st[i])        {        case'(':        case'[':        case'{':            Push(s, st[i]);            break;        case')':            Pop(s, c);            if(c!='(') d=0;            break;        case']':            Pop(s, c);            if(c!='[') d=0;            break;        case'}':            Pop(s,c);            if(c!='{') d=0;            break;        }    }    if(StackEmpty(s)&&d==1)        return true;    else        return false;}int main(){    char st[50];    printf("请输入表达式:");    scanf("%s", st);    if(isMatch(st))        printf("配对正确!!\n");    else        printf("配对错误!!\n");    return 0;}


由这几个函数运行得:

输入2+(3+4)*[2+{[3]}]-8时

输入2+(3+4*[2)+{[3]}-8时

0 0
原创粉丝点击