“栈与队列”之栈--基本数据结构
2014-02-15 13:44
309 查看
元宵已过,这还是大学以来第一次在家过元宵,之前家里一直有客人,小孩不断啊...所以,电脑基本无缘了,但是现在可以自由使用了...
之前放假回来拿了本《算法导论》,回来就真当是放假了,没怎么看,这下继续往后看...
如题,基本数据结构,话说当时学习《数据结构》时没好好学啊,后来也一直在补,对这方面也比较重视。
第一期:亡羊补牢犹未晚啊,栈,按照书上小小的操作一下,后续会有补充...
栈和队列都是动态集合,且在其上进行DELETE操作所移除的元素是预先设定的。在栈(stack)中,被删除的是最近插入的元素:即栈实现的是一种后进先出(last-in,first-out,LIFO)策略。
下面是栈的简单操作,即初始化InitStack,空栈StackEmpty,入栈Push,出栈Pop;
第二期:栈-2
由于ElemType stack[StackMaxSize],栈的坐标是从下标0开始的:
运行如下:
后续遇到会继续补上...
*∩_∩*
之前放假回来拿了本《算法导论》,回来就真当是放假了,没怎么看,这下继续往后看...
如题,基本数据结构,话说当时学习《数据结构》时没好好学啊,后来也一直在补,对这方面也比较重视。
第一期:亡羊补牢犹未晚啊,栈,按照书上小小的操作一下,后续会有补充...
栈和队列都是动态集合,且在其上进行DELETE操作所移除的元素是预先设定的。在栈(stack)中,被删除的是最近插入的元素:即栈实现的是一种后进先出(last-in,first-out,LIFO)策略。
下面是栈的简单操作,即初始化InitStack,空栈StackEmpty,入栈Push,出栈Pop;
#include<iostream> using namespace std; const int StackMaxSize = 30; //栈空间 typedef int ElemType; // 定义元素类型为整型 typedef struct Stack { ElemType stack[StackMaxSize]; //栈 int top; }STACK; void InitStack(Stack &S) { S.top = 0; } bool StackEmpty(Stack S) //判断空栈 { if(S.top == 0) return true; else return false; } void Push(Stack &S, int x) //压栈 { if(S.top == StackMaxSize) return; S.top++; S.stack[S.top] = x; } int Pop(Stack &S) //出栈,并返回此时栈顶元素 { if(S.top == 0) return -1; S.top--; return S.stack[S.top]; } int main() { STACK S; InitStack(S); if(StackEmpty(S)) cout<<"栈为空"<<endl; else cout<<"非空栈"<<endl; Push(S, 15); Push(S, 6); Push(S, 2); Push(S, 9); cout<<Pop(S)<<endl; cout<<Pop(S)<<endl; return 0; }
第二期:栈-2
由于ElemType stack[StackMaxSize],栈的坐标是从下标0开始的:
#include<iostream> using namespace std; const int StackMaxSize = 4; //栈空间 typedef int ElemType; // 定义元素类型为整型 typedef struct Stack { ElemType stack[StackMaxSize]; //栈 int top; }STACK; void InitStack(Stack &S) { S.top = -1; } bool StackEmpty(Stack S) //判断空栈 { if(S.top == -1) return true; else return false; } void Push(Stack &S, int x) //压栈 { if(S.top == StackMaxSize - 1) return; S.top++; S.stack[S.top] = x; } int Pop(Stack &S) //出栈,并返回此时栈顶元素 { if(S.top == -1) return -1; S.top--; if(S.top > -1) return S.stack[S.top]; else cout<<"已是空栈"<<endl; return 0; } int main() { STACK S; InitStack(S); if(StackEmpty(S)) cout<<"栈为空"<<endl; else cout<<"非空栈"<<endl; Push(S, 15); Push(S, 6); Push(S, 2); Push(S, 9); cout<<Pop(S)<<endl; cout<<Pop(S)<<endl; cout<<Pop(S)<<endl; cout<<Pop(S)<<endl; return 0; }将StackMaxsize改为4,在进行初始化时,top = -1;当入栈的时候,与StackMaxsize - 1比较,判断是否满了,出栈同样;
运行如下:
后续遇到会继续补上...
*∩_∩*
相关文章推荐
- 数据结构-链队列的基本操作
- 数据结构 队列的基本操作
- 数据结构(六)循环队列的基本操作 入队 退队
- 数据结构-链队列的基本操作
- 【数据结构与算法】基本数据结构——队列的链式表示
- 数据结构-循环队列的基本实现操作
- 面向数据c++数据结构之基本数据结构(队列)--【美】Jan Harrington 陈博译
- 数据结构类型定义及基本操作汇总(一)--线性表,单链表,栈和队列
- 数据结构 循环队列的基本操作
- 基本数据结构 - 栈和队列
- JS的基本数据结构实现---栈和队列
- 栈和队列数据结构的基本概念及其相关的Python实现
- 基本数据结构--表、栈和队列
- 基本数据结构,循环队列的顺序实现。
- 数据结构 链队列基本操作
- 算法导论第10章-基本数据结构-10.1栈和队列
- 基本数据结构——队列
- 第九篇:基本数据结构——队列的链式表示
- 基本数据结构的python实现---队列
- 数据结构-循环顺序队列的基本操作