C语言 之 栈
来源:互联网 发布:动态最优化课后题答案 编辑:程序博客网 时间:2024/06/08 00:43
栈
后进先出的数据结构,先存入栈的底部,往上插入,最先插入的数据先出栈。
只能向顶部加,只能从顶部删
利用数组实现栈,数组放到结构体中,结构体中包括下标、总和、数组:下标初始化比正常数组多一,便于判断栈是否为空
创建栈:stack_t* create_stack()
{
stack_t* s = (stack_t*)malloc(sizeof(stack_t));
ERROR(s, NULL);
s->top = SIZE;
s->total = SIZE;
memset(s->array, 0, sizeof(s->array));
return s;
}
栈中插入数据:从栈底插入
int push_stack(stack_t* s, int data)
{
ERROR(s, -1);
STACK_FULL(s->top, -1); //判断栈是否满了
s->top --;
s->array[s->top] = data;
return 0;
}
栈里取值
int pop_stack(stack_t* s, int* data)//利用型参保存取出的数据,传址类型
{
ERROR(s, -1);
STACK_EMPTY(s->top, -1); //是否为空,空的不许要取值
*data = s->array[s->top];
s->array[s->top] = 0; //取出后置零
s->top ++; //退入下一个位置
return 0;
}
判断栈是否为空:
int full_stack(stack_t* s)
{
ERROR(s, -1);
STACK_FULL(s, 1);
return 0;
}
int empty_stack(stack_t* s)
{
ERROR(s, -1);
STACK_EMPTY(s, 1);
return 0;
}
利用链表实现栈:
创建栈:stack_l* stack_create(int size)和
[root@Abel stack_l]# cat stack_l.c
#include "stack_l.h"
stack_l* stack_create(int size)
{
stack_l* s = (stack_l*)malloc(sizeof(stack_l));
ERROR(s, NULL);
s->top = 0;
s->total = size;
s->head = create_list();
return s;
}
[root@Abel stack_l]# cat list.c
#include"list.h"
node* create_list()
{
node* head = (node*) malloc(sizeof(node));
if(NULL == head)
{
printf("NULL\n");
exit(1);
}
head->data = 0;
head->next = NULL;
return head;
}
向栈里插入数据:int push_stack(stack_l* s, int data)
{
ERROR(s, -1);
if(s->top == s->total) //栈是否满了
{
perror("stack is full\n");
return -1;
}
insert_hlist(s->head, data); //list.c中的函数
s->top ++; //指向下一个数组
return 0;
}
遍历栈的数据:int show_stack(stack_l* s)
{
ERROR(s, -1);
if(s->top == 0)
{
perror("stack is empty\n");
return -1;
}
find_alist(s->head); //list.c中
return 0;
}
删除战中数据:int pop_stack(stack_l* s, int *data)
{
ERROR(s, -1);
if(0 == s->top)
{
perror("stack is empty\n");
return -1;
}
*data = s->head->next->data;//head中的下一个的数据
delete_hlist(s->head);
s->top —; //指向上一个
return 0;
}
- C语言 之 栈
- c语言之栈
- c语言数据结构之栈
- C语言之栈学习
- c语言之栈结构
- 数据结构之c语言栈的演示
- 数据结构C语言实现之顺序栈
- 数据结构C语言实现之链栈
- 数据结构(C语言描述)读书笔记之栈
- 数据结构之---C语言实现共享栈
- 数据结构之栈的c语言实现
- c语言之堆,栈,队列
- 数据结构之栈(C语言实现)
- 数据结构之 栈(C语言实现)
- C语言数据结构之栈篇
- C语言堆栈之顺序栈
- C语言堆栈之链栈
- C语言之四书五经
- vs2010 c++ error
- 布尔型与关系运算符的结合使用
- Flash Builder 开发相关链接
- operator int()用法
- rsa 加解密
- C语言 之 栈
- JDK环境变量配置
- Documentation/ABI/obsolute/sys-bus-usb.txt
- codeblocks 调试不停止的解决办法。
- 关于vc6程序拖拽文件WM_DROPFILE在win7,win8,vista上不能响应的解决方法
- Android之TabHost
- C语言 之 文件
- LTE射频拉远单元数字中频方案(七)
- 一元二次方程求解