栈的基本操作-数据结构
来源:互联网 发布:俄罗斯交友软件vk 编辑:程序博客网 时间:2024/06/05 03:17
栈的基本操作,顺序表动态存储。
基本操作:栈初始化,入栈,出栈,取栈顶元素,判断是否是空栈,清空栈。
例代码:
#include<stdio.h>#include<string.h>#include<malloc.h>#define Initsize 100#define Increase 100#define ERROR 0#define OK 1#define OVERFLOW -1typedef int Status;typedef int Elemtype;typedef struct SqStack{Elemtype *base,*top;int stacksize;}SqStack;//init stackStatus InitStack(SqStack &s){s.base=(Elemtype*)malloc(Initsize*sizeof(Elemtype));if(!s.base) return ERROR; s.top=s.base;s.stacksize=Initsize;return OK;}//push stackStatus Pushstack(SqStack &s,Elemtype e){Elemtype *temp;if(s.top-s.base+1>=s.stacksize)//stack full{temp=(Elemtype*)realloc(temp,(Increase+s.stacksize)*sizeof(Elemtype)); if(!temp) return ERROR;s.base=temp;s.top=s.base+s.stacksize; //remalloc changes the s.top's address,relocate s.top pointers.stacksize+=Increase; } *s.top=e;s.top++;return OK;}//stack if emptybool EmptyStack(SqStack s){if(s.base==s.top) return true;else return false;}//print stackStatus DisplayStack(SqStack s){if(EmptyStack(s)) printf("Stack is empty!\n");else{while(s.top!=s.base){s.top--;printf("%d ",*s.top);}printf("\n");}return OK;}//top elem pop stack Status PopStackelem(SqStack &s){if(EmptyStack(s)){printf("Stack is empty!\n");return ERROR;}s.top--;return OK;} //get top elemElemtype GetStacktop(SqStack s,Elemtype &e){if(EmptyStack(s)){printf("Stack is empty!\n");return ERROR;} s.top--;e=*s.top;return OK;}Status ClearStack(SqStack &s){s.top=s.base;s.stacksize=0;return OK;}int main(){SqStack stack;int n,i;Elemtype e;InitStack(stack);printf("Input n and the num:");scanf("%d",&n);for(i=0;i<n;i++){scanf("%d",&e);Pushstack(stack,e);}DisplayStack(stack); //print stackGetStacktop(stack,e); //get topif(e) printf("The top elem of stack is %d.\n",e);PopStackelem(stack); //pop stackGetStacktop(stack,e);//get topif(e) printf("The top elem of stack is %d.\n",e);DisplayStack(stack);ClearStack(stack); //clear stack DisplayStack(stack);return 0;}
0 0
- 【数据结构】 栈的基本操作
- 数据结构栈的基本操作
- 栈的基本操作-数据结构
- 【数据结构】栈的基本操作
- [数据结构]栈的基本操作
- 数据结构--栈的基本操作
- 数据结构--栈的基本操作
- 数据结构:栈的基本操作
- 数据结构-栈的基本操作
- 数据结构--栈的基本操作
- 栈的简单基本操作(数据结构)
- 数据结构---链栈的基本操作
- 数据结构--顺序栈的基本操作
- 数据结构 顺序栈的基本操作
- 数据结构 共用栈的基本操作
- 数据结构 链栈的基本操作
- 数据结构——栈的基本操作
- 数据结构第三章栈的基本操作
- 视频基础知识分享笔记
- 51单片机在Keil中使用printf进行串口输出
- C++Primer第五版 4.1.2节练习
- 转 SDL2.0在mfc窗口中显示yuv的一种方法
- iOS 基础复习
- 栈的基本操作-数据结构
- Linux系统下修改网络配置
- Lucene--Analyzer
- JS原生编写飞机大战小蜜蜂游戏
- 开源分享三(炫酷的Android Loading动画)
- 【marks】web前端资源
- Mac os X 平台 初始化 Python Pygame 库文件简便方法
- 打造自己的Vim的IDE
- linux c 中文件的创建 读写