纯C的Stack实现

    写教程,想要说明白面向过程和面向对象的区别,想用Stack作为最简单的例子。网上搜索C stack头几个写得乱七八糟。干脆自己动手写个。

=======================================stack.c============================================
#include <stdio.h>
#include <stdlib.h>

typedef struct
{
    int* elements;
    int top;
    int capacity;
} Stack;

void init(Stack* st, int capacity)
{
    st->top = 0;
    st->capacity = capacity;
    st->elements = (int*)malloc(sizeof(int) * capacity);
}
void destory(Stack* st)
{
    if (st->elements != NULL)
    {
        free(st->elements);
        st->elements = NULL;
    }
}
int isFull(Stack* st)
{
    return (st->top >= st->capacity);
}
void push(Stack* st, int val)
{
    st->elements[st->top] = val;
    (st->top)++;    
}
int isEmpty(Stack* st)
{
    return (st->top == 0);
}
int pop(Stack* st)
{
    (st->top)--;
    return (st->elements[st->top]);  
}
int size(Stack* st)
{
    return (st->top);
}
int capacity(Stack* st)
{
    return (st->capacity);
}
void print(Stack* st)
{
    int i = 0;
    if (st->top == 0)
    {
        printf("stack is empty.\n");
    }
    else
    {
        printf("stack contents: ");
        for (i = 0; i < st->top; i++)
        {
            printf("%d, ",st->elements[i]);
        }
        printf("\n");
    }
}

int main()
{
    Stack st;
    int i = 0;   
    init(&st, 10);
    isEmpty(&st) ? printf("stack is empty\n") : printf("stack is not empty\n");
    isFull(&st) ? printf("stack is full\n") : printf("stack is not full\n");
    for (i = 0; i < 10; i++)
    {
        push(&st, i);
        printf("push %d\n", i);
    }
    isEmpty(&st) ? printf("stack is empty\n") : printf("stack is not empty\n");
    isFull(&st) ? printf("stack is full\n") : printf("stack is not full\n");
    for (i = 0; i < 5; i++)
    {
        printf("pop %d\n", pop(&st));
    }
    isEmpty(&st) ? printf("stack is empty\n") : printf("stack is not empty\n");
    isFull(&st) ? printf("stack is full\n") : printf("stack is not full\n");
    printf("capacity of stack is %d, size of statck is %d\n", capacity(&st), size(&st));
    print(&st);
    destory(&st);
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值