美文网首页
栈的实现

栈的实现

作者: Drs莫思归 | 来源:发表于2017-12-21 15:05 被阅读0次

    include <stdio.h>

    include <stdlib.h>

    define STACK_INIT_SIZE 100

    define INCRE 10

    define ERROR -1

    define OK 1

    typedef struct{
    int *base;
    int *top;
    int stacksize;
    }SqStack;
    int InitStack(SqStack *S){
    S->base = (int *)malloc(STACK_INIT_SIZE * sizeof(int));
    if(!S->base) return ERROR;
    S->top = S->base;
    S->stacksize = STACK_INIT_SIZE;
    return OK;
    }
    int Print(SqStack S){
    int *i = S.top;
    if(S.base == S.top)
    return ERROR;
    while(i > S.base){
    i--;
    printf("%d ", *i);
    }
    putchar('\n');
    return OK;
    }
    void CreadStack(SqStack S, int n){
    printf("请输入%d个元素:", n);
    int i = 0;
    while(i < n){
    scanf("%d", S->top);
    S->top++;
    i++;
    }
    Print(
    S);
    }
    int GetTop(SqStack *S, int num){
    if(S->base == S->top)
    return ERROR;
    num = *(S->top-1);
    printf("top: %d\n", num);
    return OK;
    }
    int Push(SqStack *S, int num){
    if(S->top - S->base >= S->stacksize){
    S->base = (int )realloc(S->base, (S->stacksize+INCRE)sizeof(int));
    if(!S->base){
    return ERROR;
    }
    S->top = S->base + S->stacksize;
    S->stacksize += INCRE;
    }
    (S->top++) = num;
    Print(
    S);
    return OK;
    }
    int Pop(SqStack *S, int num){
    if(S->top == S->base){
    return ERROR;
    }
    num = --S->top;
    printf("Pop:%d\n", num);
    Print(
    S);
    return OK;
    }
    int Show(){
    int n;
    printf("*****************\n");
    printf("1、获取栈顶元素。\n");
    printf("2、插入元素。\n");
    printf("3、删除栈顶元素。\n");
    printf("4、退出。\n");
    printf("-----------------\n");
    printf("请选择要操作的序号:");
    scanf("%d", &n);
    return n;
    }
    int main()
    {
    SqStack S;
    int num = 0;
    InitStack(&S);
    CreadStack(&S, 5);
    int sele = Show();
    while(sele != 4){
    switch(sele){
    case 1:
    GetTop(&S, num);
    sele = Show();
    break;
    case 2:
    printf("请输入要进栈的数字:");
    scanf("%d", &num);
    Push(&S, num);
    sele = Show();
    break;
    case 3:
    Pop(&S, num);
    sele = Show();
    break;
    case 4:
    break;
    }
    }
    return 0;
    }

    相关文章

      网友评论

          本文标题:栈的实现

          本文链接:https://www.haomeiwen.com/subject/vodawxtx.html