第6周项目1建立顺序栈算法库
2015-10-09 09:04
302 查看
问题及代码:
(1)main.cpp
(2)sqstack.cpp
(3)sqstzck.h
运行结果:
知识点总结:
栈的建立及输出,进栈及出栈
学习心得:
栈与链表的学习相通,还是要学好链表,循序渐进。
(1)main.cpp
/* 文件名称:项目1.cpp 作者:孙洁 完成日期:2015.10.9 问题描述: 定义顺序栈存储结构,实现其基本运算,并完成测试。 输入描述: 无 程序输出: 若干数据 */ #include <stdio.h> #include "sqstack.h" 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; }
(2)sqstack.cpp
#include <stdio.h> #include <malloc.h> #include "sqstack.h" void InitStack(SqStack *&s) { s=(SqStack *)malloc(sizeof(SqStack)); s->top=-1; } void DestroyStack(SqStack *&s) { free(s); } int StackLength(SqStack *s) //返回栈中元素个数——栈长度 { return(s->top+1); } bool StackEmpty(SqStack *s) { return(s->top==-1); } bool Push(SqStack *&s,ElemType e) { if (s->top==MaxSize-1) //栈满的情况,即栈上溢出 return false; s->top++; s->data[s->top]=e; return true; } bool Pop(SqStack *&s,ElemType &e) { if (s->top==-1) //栈为空的情况,即栈下溢出 return false; e=s->data[s->top]; s->top--; 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; for (i=s->top;i>=0;i--) printf("%c ",s->data[i]); printf("\n"); }
(3)sqstzck.h
#ifndef SQSTACK_H_INCLUDED #define SQSTACK_H_INCLUDED #define MaxSize 100 typedef 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 // SQSTACK_H_INCLUDED
运行结果:
知识点总结:
栈的建立及输出,进栈及出栈
学习心得:
栈与链表的学习相通,还是要学好链表,循序渐进。
相关文章推荐
- 第六周--项目5后缀表达式
- jQuery Mobile基础08----jQuery Mobile Widgets(2)-navbar(导航
- Struct结构体的使用学习
- 软件测试分类基本概念
- nodeJS压缩图片/JS/CSS
- eclipse中tomcat在debug模式下有时会自动跳转到processWorkerExit(w, completedAbruptly);中的问题
- jQuery的发展史,你知道吗?
- 第四周项目3 单链表应用(3)
- 第六周 项目3-括号的匹配
- 修改产品的group price的值,修改为如下形式: 41.78 => 41.95 55.88 => 55.95
- WampServer下如何实现多域名配置
- 浅入深出的理解了盒模型,哈哈哈
- 勤奋,加快学习进度!
- 第四周项目1 建立单链表
- 项目5 -- 后缀表达式
- jQuery Mobile基础07----jQuery Mobile Widgets(2)-listview(列表视图
- 第4周 项目2-建设“单链表”算法库
- iOS 8 新特性介绍
- linux 如何显示和删除隐含文件
- JavaScript实现九九乘法表