您的位置:首页 > 其它

纯C的Stack实现

2015-10-10 09:21 411 查看
   
写教程,想要说明白面向过程和面向对象的区别,想用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;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: