栈的实现及应用
来源:互联网 发布:网络骗局大全 编辑:程序博客网 时间:2024/05/17 00:10
1.栈是先入后出的数据结构,它的实现可以用数组或者栈顶指针表示,用数组时,可以为栈预分配一定的大小,栈为空时,下标值为top为-1,每增加一个元素,下标值加1,出栈时,弹出一个元素,下标值减1,判断栈是否为空可以用下标值top是否为-1。
# include <stdio.h># include <stdlib.h>int stack[100]={};int top=-1;int size=100;int main(){void push(int a[],int);int pop(int a[]);int isempty(int a[]);push(stack,1);push(stack,2);push(stack,3);printf("%d\n",isempty(stack));printf("%d\n",pop(stack));printf("%d\n",pop(stack));system("pause");return 0;}void push(int a[],int x){if(top>=size)printf("out of range");elsetop++; stack[top]=x;}int pop(int a[]){if (top==-1){printf("stack is empty");exit(-1);}return a[top--]; }int isempty(int a[]){return top==-1;}
2.栈也可以用指针来实现,定义结构体表示一个节点,每个节点包含两个元素,一个是节点的数据值,另外一个是前驱指针。栈的入栈操作示意图为
# include <stdio.h># include <stdlib.h>struct node{int num;struct node *next;};typedef struct node *link;int main(){link stack=NULL;link push(link,int);int pop(link);int isempty(link);link s=push(stack,1);s=push(s,2);s=push(s,3);printf("%d\n",pop(s));printf("%d\n",isempty(s));system("pause");return 0;}link push(link stack,int x){link newele=(link)malloc(sizeof(node));if(!newele)exit(-1);newele->next=stack;newele->num=x;stack=newele;return stack;}int pop(link stack){if(!stack)return -1;int t;link temp=stack;stack=stack->next;t=temp->num;free(temp);return t;}int isempty(link stack){return stack==NULL;}
3栈的应用
栈可以用于把十进制数转换为其它进制,如将十进制转换为8进制,N=(N/8)*8+N%8,将N除以8取商,最后将商值反过来写,即得到对应的八进制数,这刚好和栈的性质类似,下面用数组实现一个栈,并用此栈实现进制数转换。
# include <stdio.h># include <stdlib.h>int stack[100]={};int top=-1;int size=100;int main(){ int t;void push(int a[],int);int pop(int a[]);int isempty(int a[]);printf("input the decimal number\n"); scanf("%d",&t);if(t>0){while(t){push(stack,t%8);t=t/8;}while(!isempty(stack)){printf("%d",pop(stack));}}else{t=-t;while(t){push(stack,t%8);t=t/8;}printf("-");while(!isempty(stack)){printf("%d",pop(stack));}}printf("\n");system("pause");return 0;}void push(int a[],int x){if(top>=size)printf("out of range");elsetop++; stack[top]=x;}int pop(int a[]){if (top==-1){printf("stack is empty");exit(-1);}return a[top--]; }int isempty(int a[]){return top==-1;}
0 0
- 栈的实现及应用
- 栈的实现及应用
- 栈(Stack)的python实现及应用
- Ioc的实现及应用
- Ioc的实现及应用
- 遮罩层的实现及应用
- CocurrentHashMap的应用及实现
- 栈的实现及应用学习笔记--Java实现
- 栈的表示与实现及栈的应用
- Python实现栈,及栈的应用实例
- 验证性实验三 栈、队列的实现及应用
- 数据结构—栈的实现及实战应用
- 遗传算法的C#实现及应用
- 遗传算法的C#实现及应用
- PIMPL 模式的实现及应用。
- PIMPL 模式的实现及应用
- BiDi 算法的实现及应用
- java实现队列及队列的应用
- 【phpcms-v9】整理资料
- 异步请求url带有中文参数,防止因空格报错
- linux yum命令详解
- js创建对象的几种常用方式
- Linux添加/删除用户和用户组
- 栈的实现及应用
- SQL 中的escape
- hdu 1233 还是畅通工程
- hello world
- Rational Rose2003破解
- SQLquery.addScalar
- C++回顾之const对象、const成员函数、mutable类型
- Emoji表情
- OPENGL基础