zoukankan      html  css  js  c++  java
  • 数据结构实验报告顺序栈的应用代码分析

    一、源代码的预定义部分

    预定义部分提供了头文件和宏定义的内容,是代码的功能实现基础。

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #define STACK_INIT_SIZE 100
    #define STACKINCREMENT 10
    #define MAXSIZE 30
    #define OVERFLOW 0
    #define ERROR 0
    #define OK 1
    #define T 1
    #define F 0

    二、顺序栈的方法操作

    注意这里的方法有具体的返回类型,请读者自行参考代码的具体实现。

    typedef char ElemType;
    // 定义顺序栈结构体
    typedef struct{
        ElemType *base;
        ElemType *top;
        int stackSize;
    }SqStack;
    // 初始化顺序栈
    int InitStack(SqStack &S){
        S.base=(ElemType *)malloc(STACK_INIT_SIZE*sizeof(ElemType));
        if(!S.base) return OVERFLOW;
        S.top=S.base;
        S.stackSize=STACK_INIT_SIZE;
        return OK;
    }
    // 判空操作
    int IsEmpty(SqStack S){
        if(S.top==S.base) return T;
        return F;
    }
    // 入栈操作
    int push(SqStack &S, ElemType e){
        if(S.top-S.base>=S.stackSize){
            S.base=(ElemType *)realloc(S.base,
            (S.stackSize+STACKINCREMENT)*sizeof(ElemType));
            if(!S.base) return OVERFLOW;
            S.top=S.base+S.stackSize;
            S.stackSize+=STACKINCREMENT;
        }
        *(S.top++)=e;
        return OK;
    }
    // 取栈顶元素
    char GetTop(SqStack S, ElemType &e){
        if(IsEmpty(S)) return ERROR;
        e=*(S.top-1);
        return e;
    }
    // 出栈操作
    char pop(SqStack &S, ElemType &e){
        if(IsEmpty(S)) return ERROR;
        e=*(S.top-1);
        S.top--;
        return e;
    }

    三、main方法的结构化程序

    int main(){
        char a[MAXSIZE]={};
        char m,n;
        printf("请输入字符串序列:");
        scanf("%s",a);
        getchar();
        int length=(int)strlen(a);
        SqStack S;
        InitStack(S);
        
        for(int i=0;i<length;i++){
            if(a[i]=='('||a[i]=='{'||a[i]=='['){
                push(S, a[i]);
            }else{
                if(a[i]==')'){
                    if(GetTop(S, m)=='('){
                        pop(S, n);
                    }
                }
                if(a[i]=='}'){
                    if(GetTop(S, m)=='{'){
                        pop(S, n);
                    }
                }
                if(a[i]==']'){
                    if(GetTop(S, m)=='['){
                        pop(S, n);
                    }
                }
            }
        }
        if(IsEmpty(S)){
            printf("括号匹配");
        }else{
            printf("括号不匹配");
        }
        return 0;
    }

    其实消消乐游戏就是受到括号匹配算法的启发!

    爱我没结果!
  • 相关阅读:
    hdu2328 Corporate Identity
    hdu1238 Substrings
    hdu4300 Clairewd’s message
    hdu3336 Count the string
    hdu2597 Simpsons’ Hidden Talents
    poj3080 Blue Jeans
    poj2752 Seek the Name, Seek the Fame
    poj2406 Power Strings
    hust1010 The Minimum Length
    hdu1358 Period
  • 原文地址:https://www.cnblogs.com/angoli/p/12684223.html
Copyright © 2011-2022 走看看