顺序栈(C语言,静态栈)

代码部分

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>

#define INITSIZE 4
#define INCREMENT 2

typedef struct stack {
    int *base;
    int top;
    int size;
}STACK, *PSTACK;

void init(PSTACK);
bool is_empty(PSTACK);
bool is_full(PSTACK);
bool push(PSTACK, int);
void traverse(PSTACK);
bool pop(PSTACK, int *);
// 栈有效元素(节点)为top + 1
void clear(PSTACK);
void destroy(PSTACK);

void destroy(PSTACK p)
{
    if (is_empty(p))
        return;

    free(p->base);
    p->top = -1;
    p->size = 0;
}

// 只是更新栈顶,栈所占内存还在
void clear(PSTACK p)
{
    printf("清空栈\n");
    if (is_empty(p))
        return;

    p->top = -1;
}

bool pop(PSTACK p, int *pVal)
{
    printf("pop...");
    if (is_empty(p)){
        printf("栈空!\n");
        return false;
    }

    *pVal = p->base[p->top--];

    printf("成功 值为%d\n", *pVal);
    return true;
}

void traverse(PSTACK p)
{
    printf("遍历(显示顺序栈顶=>栈底)\n");
    if (is_empty(p)) {
        printf("栈空!\n");
        return;
    }

    for (int i=p->top; i >=0; --i) {
        printf("%d\n", p->base[i]);
    }
}

bool push(PSTACK p, int val)
{
    printf("push %d", val);
    if (is_full(p)) {
        p->base = (int *)realloc(p->base, sizeof(int) * (INCREMENT + p->size));
        p->size += INCREMENT;
        if (! p->base) {
            printf(" 栈满自动扩展空间失败!\n");
            return false;
        }
        else
            printf(" 栈满自动扩展空间");
    }

    p->base[++p->top] = val;

    printf(" 成功\n");
    return true;
}

bool is_full(PSTACK p)
{
    // 因为是数组下标从0开始
    if (p->top == p->size - 1)
        return true;
    return false;
}

bool is_empty(PSTACK p)
{
    if (p->top == -1)
        return true;
    return false;
}

void init(PSTACK p)
{
    p->base = (int *)malloc(sizeof(int) * INITSIZE);
    p->top = -1;
    p->size = INITSIZE;
}

int main(void)
{
    STACK S;
    int val;

    init(&S);
    push(&S, 1);
    push(&S, 2);
    push(&S, 3);
    push(&S, 4);
    push(&S, 5);
    push(&S, 6);
    traverse(&S);
    pop(&S, &val);
    pop(&S, &val);
    pop(&S, &val);
    traverse(&S);
    clear(&S);

    return 0;
}

猜你喜欢

转载自blog.51cto.com/sndapk/2666171