数据结构——栈
2016-01-25 15:39
471 查看
一:动态数组堆栈
用一个指针代替数组,然后可以用malloc函数来动态建立一个大小由自己定的数组代码如下:
#include<stdio.h> #include<string.h> #include<stdlib.h> int *s; int stacksize; int top = -1; void create(int num) //建立一个空栈 { stacksize = num; s= (int*)malloc(stacksize*sizeof(int)); //动态数组 } void push(int e) //入栈函数 { s[++top] = e; } int gettop() //取得栈顶元素 { return s[top]; } void pop() //删除栈顶元素 { top--; } int main() { int size; scanf("%d", &size); create(size); push(1); push(2); while (top != -1) { printf("%d ", gettop()); pop(); } printf("\n"); return 0; }
二:链式堆栈
用链表表示栈,可以插入一个分配一个空间,就不用一开始分配空间了代码如下:
#include<stdio.h> #include<string.h> #include<stdlib.h> typedef struct node { int data; struct node *next; }TYPE; TYPE *s; void push(int e) { TYPE *newnode; newnode = (TYPE*)malloc(sizeof(TYPE)); newnode->data = e; newnode->next = s; s = newnode; } void pop() { TYPE *newnode; newnode = s; s = s->next; free(newnode); } void print() { TYPE *stack; stack = s; while (stack != NULL) { printf("%d ", stack->data); stack = stack->next; } printf("\n"); } int gettop() { return s->data; } int is_empty() //判断栈是否为空栈函数 { return s == NULL; } void clean() //清空整个分配空间函数 { while (!is_empty) pop(); } int main() { push(10); push(9); push(7); push(6); push(5); push(4); push(3); push(2); push(1); push(0); printf("push压入数值后:\n"); print(); printf("\n"); pop(); pop(); printf("经过pop弹出几个元素后的堆栈元素:\n"); print(); printf("\n"); printf("top()调用出来的值: %d\n", gettop()); clean(); return 0; }
相关文章推荐
- 数据结构之Shapefile
- 数据结构之队列
- 数据结构之栈
- Shapefile数据结构
- 数据结构学习笔记——数组与矩阵压缩
- Redis 之数据结构
- 51nod1109 01组成的倍数 数据结构
- 七.学习数据结构之树
- C++ —— 数据结构之 顺序栈,链式栈?
- UVA 12096 The SetStack Computer
- 六.学习数据结构之递归
- opencv从入门到精通(4)--IplImage数据结构
- 学习STL map, STL set之数据结构基础
- 2015年大二上-数据结构-图-1-(4)-利用遍历思想求解图问题(2)
- 2015年大二上-数据结构-图-1-(4)-利用遍历思想求解图问题(1)
- 数据结构(寒假小结)——2.线性表
- 小蚂蚁学习数据结构(23)——伪代码中的引用
- PHP——数组和数据结构
- LeetCode12. Integer to Roman不用任何数据结构和数组
- 查找链表倒数第K个节点