栈的顺序存储的实现与操作

来源:互联网 发布:西安交通大学软件学院 编辑:程序博客网 时间:2021/01/23 05:28

栈的顺序存储的实现与操作

顺序栈就像是一个记录了开头和结尾的下标的数组,并且只能在尾部添加和删除结点

示例代码

#include <stdio.h>#include <stdlib.h>#define STACK_INIT_SIZE 100#define STACKINCREMENT 10typedef struct{    char *base;    char *top;    char StackSize;}SeqStack;int InitStack(SeqStack *S);int iSeMPTY(SeqStack *S);int Push(SeqStack *S, char x);int Pop(SeqStack *S, char *x);int GetTop(SeqStack S, char *e);print_S(SeqStack S);int main(void){    char ch;    SeqStack S;    if(!InitStack(&S)){        printf("顺序栈初始化失败!\n");        exit(1);    }    printf("顺序栈初始化成功!\n");    int end = 0;    int ope;    while(!end){        print_hyphen(15); printf("\n");        printf("请输入指令来执行操作\n");        print_hyphen(15); printf("\n");        printf("1、判断栈是否为空\n2、入栈一个元素\n3、出栈一个元素\n4、获取栈顶元素\n5、退出\n");        print_hyphen(15); printf("\n");        printf("输入要使用的功能的序号: ");        scanf("%d", &ope);        switch(ope){            case 1:                if(iSeMPTY(&S))                    printf("栈为空!\n");                else                    printf("栈不为空!\n");                break;            case 2:                printf("请输入要入栈的字符: ");                scanf(" %c", &ch);                Push(&S, ch);                print_S(S);                break;            case 3:                Pop(&S, &ch);                printf("出栈的元素为 %c\n", ch);                print_S(S);                break;            case 4:                GetTop(S, &ch);                printf("栈顶元素为 %c\n", ch);                print_S(S);                break;            case 5:                printf("再见!\n");                end = 1;                break;            default:                printf("无此序号,请重新输入!\n");        }    }    return 0;}int InitStack(SeqStack *S){    S->base = (char *)malloc(STACK_INIT_SIZE*sizeof(char));    if(!S->base)        exit(1);    else{        S->top = S->base;        S->StackSize = STACK_INIT_SIZE;    }    return 1;}int iSeMPTY(SeqStack *S){    if(S->top == S->base)        return 1;    else        return 0;}int Push(SeqStack *S, char x){    if((S->top)-(S->base) == S->StackSize){        S->base = (char *)realloc(S->base, (S->StackSize+STACKINCREMENT)*sizeof(char));        if(S->base == NULL)            return 0;        S->top = S->base+S->StackSize;        S->StackSize = S->StackSize+STACKINCREMENT;    }    *S->top = x;    S->top++;    return 1;}int Pop(SeqStack *S, char *x){    if(S->top == S->base)        return 0;    else{        S->top--;        *x = *S->top;        return 1;    }}int GetTop(SeqStack S, char *e){    if(S.top == S.base)        return 0;    *e = *(S.top-1);    return 1;}print_S(SeqStack S){    if(S.top == S.base-1)        printf("当前栈为空!\n");    printf("当前栈中的元素为:\n");    char *ch = S.top-1;    while(ch != S.base-1){        printf("%c ", *ch);        ch--;    }    printf("\n");}void print_hyphen(int n){    while(n--)        printf("-");}