注册 登录
编程论坛 数据结构与算法

新手发个括号匹配栈程序

ehszt 发布于 2017-03-14 15:41, 2347 次点击
各位好,本人正在学数据结构,发个自己刚打的代码
#define OK 1
#define SElemType char
#define STACK_INIT_SIZE 100
#define STACKINCREMENT 10
#define OVERFLOW 0
#define ERROR 0
#define TRUE 1;
#define FALSE 0;
#include <stdio.h>
#include <stdlib.h>
char map[7]={'(',')','[',']','{','}'};
typedef bool Status;

typedef struct{
    SElemType *base;
    SElemType *top;
    int stacksize;
}SqStack;

Status StackEmpty(SqStack S)
{
    if(S.top==S.base)return TRUE;
    return FALSE;
}

Status DestroyStack(SqStack &S)
{
    SElemType *temp;
    while(S.top!=S.base)
    {
        temp=S.top;
        free(temp);
        S.top--;
    }
    free(S.top);
    S.stacksize=0;
    return TRUE;
}

Status ClearStack(SqStack &S)
{
    SElemType *temp;
    while(S.top!=S.base)
    {
        *S.top--=0;
    }
    *S.top=0;
    return TRUE;
}

Status GetTop(SqStack S,SElemType &e)
{
    if(S.top==S.base)return ERROR;
    e=*(S.top-1);
    return OK;
}

Status InitStack(SqStack &S)
{
    S.base=(SElemType *)malloc(STACK_INIT_SIZE*sizeof(SElemType));
    if(!S.base)exit(OVERFLOW);
    S.top=S.base;
    S.stacksize=STACK_INIT_SIZE;
    return OK;
}

Status Push(SqStack &S,SElemType e)
{
    if(S.top-S.base>=S.stacksize)
    {
        S.base=(SElemType *)realloc(S.base,(S.stacksize+STACKINCREMENT)*sizeof(SElemType));
        if(!S.base)exit(OVERFLOW);
        S.top=S.base+S.stacksize;
        S.stacksize+=STACKINCREMENT;
    }
    *S.top++=e;
    return OK;
}

Status Pop(SqStack &S,SElemType &e)
{
    if(S.top==S.base)return ERROR;
    e=*--S.top;
    return OK;
}

main()
{
    char e,ch,flag;
    char a[200],i=0;
    SqStack S;
    InitStack(S);
    while((e=getchar())!='\n')
    {
        a[i++]=e;
        flag=0;
        for(int j=0;j<6;j++)
        {
            if(map[j]==e)
            {
                flag=1;
                break;
            }
        }
        GetTop(S,ch);
        if(ch!=(e-2)&&ch!=(e-1)&&flag)
        Push(S,e);
        else if((ch==(e-2)||ch==(e-1))&&flag)
        Pop(S,ch);
    }
    putchar('\n');
    for(int j=0;j<i;j++)
    {
        putchar(a[j]);
    }
    if(StackEmpty(S))puts("\n括号匹配!");
    else puts("\n括号不匹配!");
}

[此贴子已经被作者于2017-3-14 15:45编辑过]

2 回复
#2
九转星河2017-03-19 08:46
我也是数据结构刚起步~
#3
Hzou2017-11-07 21:48
起步+1
1