纯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;
}
相关文章推荐
- 分析软件需求说明书利弊(附某人的…
- 更改QTreeView, QListView在window…
- QTableWidget美化细节
- Android 中 Fragment的使用大全
- 单元测试:实践者的总结和反思
- VS2008性能测试profiling系统重启…
- c10k测试:使用asio实现多线程回显…
- c10k测试:每连接新线程回显服务器…
- perl脚本file处理模块展示
- 【读书笔记】iOS网络-HTTP-URL结构
- 【读书笔记】iOS网络-HTTP-URL结构
- boost智能指针的性能测试
- static、extern、无修饰符全局变量…
- 教程:多线程编程技术(上)
- 多线程设计模式:Future模式
- 多线程设计模式:Guarded Suspensi…
- Java中条件变量使用示例及性能测试
- ESP8266 学习笔记 一、 初识WSP8266
- Linux下scp的用法
- boost条件变量使用示例及性能测试