C语言实现顺序栈(NOT C++)

2018-05-02  本文已影响0人  obsession_me
#include <stdio.h>
#include <stdlib.h>

#define STACK_INIT_SIZE 100
#define SINCREASEMENT 10

typedef int ElemType;

typedef struct stack
{
    ElemType *base;
    ElemType *top;
    int stack_size;
}stack, *ListStack;

void init(ListStack S){
    // 分配空间
    S -> base = malloc(STACK_INIT_SIZE*sizeof(ElemType));
    if (!S->base){
        exit(1);  // 分配空间失败
    }
    S -> top = S -> base;
    S -> stack_size = STACK_INIT_SIZE;
}

// 销毁栈
void destory(ListStack S){
    S->top = NULL;
    free(S->base);
    S->stack_size = 0;
}

// 销毁栈
void clear(ListStack S){
    S->top = S->base;
}

// 判断栈是否为空
int isEmpty(stack s){
    if (s.base == s.top){
        return 1;
    }else{
        return 0;
    }
}

// 求栈的长度
int length(stack s){
    // return (s->top - s->base)/sizeof(ElemType);
    return (s.top - s.base);
}

// pop
void pop(ListStack s, ElemType *e){
    if (s->top == s->base){
        exit(1);  // empty stack
    }else{
        s->top--;
        e = s->top;
    }
}

// push
void push(ListStack s, ElemType e){
    // 需要考虑空间的问题
    if ((s->top - s->base) >= s->stack_size){
        s -> base = (ElemType *)realloc(s->base, (s->stack_size + SINCREASEMENT)*sizeof(ElemType));
        if (!s->base){
            exit(1); // error
        }
        // 栈底的位置可能改变
        s-> top = s->base + s->stack_size;
        s ->stack_size += SINCREASEMENT;
    }
    *(s-> top) = e;  // error s->top = &e;
    s-> top++;
}

// 得到栈顶元素 
ElemType getTop(stack s){
    if (s.top == s.base){
        return (ElemType) -1;
    }else{
        return *--s.top;
    }
}

// 遍历栈 recurrsion
void iteration_stack(stack s){
    if (s.top != s.base){
        ElemType e = getTop(s);
        s.top--; 
        printf("value: %d\n", e);
        iteration_stack(s);
    }
}


int main(){
    stack Lstack;
    init(&Lstack);
    for (int i=0; i<10; i++){
        push(&Lstack, i);
    }
    iteration_stack(Lstack);
    // printf("top is: %d\n", getTop(Lstack));
    return 0;
}

运行结果如下:

value: 9
value: 8
value: 7
value: 6
value: 5
value: 4
value: 3
value: 2
value: 1
value: 0
请按任意键继续. . .
上一篇 下一篇

猜你喜欢

热点阅读