第五周-【项目1
来源:互联网 发布:js实现图片轮播解析 编辑:程序博客网 时间:2024/05/22 06:50
本篇博客是介绍栈的基本算法即建立其算法库,算法库的结构使用主函数包含头文件的形式构成的,头文件里包括八个基本栈的算法,然后在.cpp文件里定义它们。
首先是头文件:
/* *COPYRIGTH (c) 2017, YTU CS *All rigth reserve *作者:王铭泽 *完成日期:2017.9.27 *版本号:v1.0 * *问题描述:顺序栈的基本算法库建立。*注:所有代码除了标准命名外全为自己coding.*/ #ifndef W_H_INCLUDED#define W_H_INCLUDED#define maxsize 100typedef char ElemType;typedef struct{ ElemType data[maxsize]; int top;}SqStack;void InitStack(SqStack *&s); //初始化栈void DestroyStack(SqStack *&s); //销毁栈bool StackEmpty(SqStack *s); //栈是否为空int StackLength(SqStack *s); //返回栈中元素个数——栈长度bool Push(SqStack *&s,ElemType e); //入栈bool Pop(SqStack *&s,ElemType &e); //出栈bool GetTop(SqStack *s,ElemType &e); //取栈顶数据元素void DispStack(SqStack *s); //输出栈#endif // W_H_INCLUDED其次是与头文件绑定的.cpp文件:
#include<stdio.h>#include<malloc.h>#include"w.h"void InitStack(SqStack *&s) //初始化栈{ s=(SqStack *)malloc(sizeof(SqStack)); s->top=-1;}void DestroyStack(SqStack *&s) //销毁栈{ free(s);}bool StackEmpty(SqStack *s) //栈是否为空{ return s->top==-1;}int StackLength(SqStack *s) //返回栈中元素个数——栈长度{ return s->top+1;}bool Push(SqStack *&s,ElemType e) //入栈{ if(s->top==maxsize-1) return false; s->data[++s->top]=e; return true;}bool Pop(SqStack *&s,ElemType &e) //出栈{ if(s->top==-1) return false; s->data[s->top--]=e; return true;}bool GetTop(SqStack *s,ElemType &e) //取栈顶数据元素{ if(s->top==-1) return false; e=s->data[s->top]; return true;}void DispStack(SqStack *s) //输出栈{ int i=s->top; for(i;i>-1;i--) { printf("%c ",s->data[i]); printf("\n"); }}
这六个基本算法是栈的基本运算,也是各种数据结构算法的基本套路。
最后是主函数即测试函数:
#include <iostream>#include"w.h"#include<stdio.h>using namespace std;int main(){ ElemType e; SqStack *s; printf("(1)初始化栈s\n"); InitStack(s); printf("(2)栈为%s\n",(StackEmpty(s)?"空":"非空")); printf("(3)依次进栈元素a,b,c,d,e\n"); Push(s,'a'); Push(s,'b'); Push(s,'c'); Push(s,'d'); Push(s,'e'); printf("(4)栈为%s\n",(StackEmpty(s)?"空":"非空")); printf("(5)栈长度:%d\n",StackLength(s)); printf("(6)从栈顶到栈底元素:");DispStack(s); printf("(7)出栈序列:"); while (!StackEmpty(s)) { Pop(s,e); printf("%c ",e); } printf("\n"); printf("(8)栈为%s\n",(StackEmpty(s)?"空":"非空")); printf("(9)释放栈\n"); DestroyStack(s); return 0;}
然后是运行结果:
阅读全文
0 0
- 第五周项目1
- 第五周项目1
- 第五周 项目1
- 第五周项目1
- 第五周项目1
- 第五周【项目1
- 第五周 【项目1
- 第五周项目1
- 第五周项目1
- 第五周-【项目1
- 第五周 项目1
- 第五周 【项目1
- 第五周 项目 1
- 第五周 项目1
- 第五周 【项目1
- 第五周项目1
- 第五周-项目1
- 第五周【项目1
- 自动化运维,安装提权工具
- Nginx配置https,加重定向强制跳转
- mongo三个索引字段复合索引的索引前缀Prefixes
- SpringBoot简单登录注册-注册(附源码)
- leetcode 148. Sort List
- 第五周-【项目1
- [FAQ19312]Android7.0状态栏信号格显示感叹号
- 如何修改mysql的密码
- 历经 33 天,终于拿到了心仪的 Offer
- 高效工作
- struts2的工作原理
- 离散时间LTI系统
- Python2.7字符编码详解
- SqlServer stuff + for xml path 用法(以权限角色管理为例讲解)