【栈项目2 - 建立链栈算法库--第6周】
来源:互联网 发布:朝闻道 刘慈欣 知乎 编辑:程序博客网 时间:2024/05/18 22:14
建立链栈算法库
list.h
writer:xujiping from yantai university#include <stdio.h>#include <malloc.h>typedef char ElemType;typedef struct linknode{ ElemType data; //数据域 struct linknode *next; //指针域} LiStack; //链栈类型定义void InitStack(LiStack *&s); //初始化栈void DestroyStack(LiStack *&s); //销毁栈int StackLength(LiStack *s); //返回栈长度bool StackEmpty(LiStack *s); //判断栈是否为空void Push(LiStack *&s,ElemType e); //入栈bool Pop(LiStack *&s,ElemType &e); //出栈bool GetTop(LiStack *s,ElemType &e); //取栈顶元素void DispStack(LiStack *s); //输出栈中元素
list.cpp
#include "list.h"void InitStack(LiStack *&s)//初始化栈{ s=(LiStack *)malloc(sizeof(LiStack)); s->next=NULL;}void DestroyStack(LiStack *&s) //销毁栈{ LiStack *p=s->next; while(p!=NULL) { free(s); s=p; p=p->next; } free(s);}bool StackEmpty(LiStack *s) //判断栈是否为空{ return(s->next==NULL);}void Push(LiStack *&s,ElemType e)//入栈{ LiStack *p; p=(LiStack *)malloc(sizeof(LiStack)); p->data=e; //新建元素e对应的节点*p p->next=s->next; //插入*p节点作为开始节点 s->next=p;}bool Pop(LiStack *&s,ElemType &e) //出栈{ LiStack *p; if(s->next==NULL) { return false; } p=s->next; e=p->data; s->next=p->next; free(p); return true;}bool GetTop(LiStack *s,ElemType &e) //取栈顶元素{ if (s->next==NULL) //栈空的情况 return false; e=s->next->data; return true;}void DispStack(LiStack *s) //输出栈中元素{ LiStack *p=s->next; while(p!=NULL) { printf("%c",p->data); p=p->next; } printf("\n");}int StackLength(LiStack *s) //返回栈长度{ int i=0; LiStack *p; p=s->next; while (p!=NULL) { i++; p=p->next; } return(i);}
main.cpp
#include "list.h"int main(){ ElemType e; LiStack *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
- 第6周项目2 -建立链栈算法库
- 第6周项目2-建立链栈算法库
- 第6周项目2--建立链栈算法库
- 第6周项目2--建立链栈算法库
- 第6周 项目2-建立链栈算法库
- 第6周 项目2-建立链栈算法库
- 【第6周 项目2 - 建立链栈算法库】
- 第6周项目2-建立链栈算法库
- 第6周项目2建立链栈算法库
- 第6周项目2-建立栈链算法库
- 第6周 项目2 - 建立链栈算法库
- 第6周 项目2-建立链栈算法库
- 第6周项目2 建立链栈算法库
- 第6周项目2 建立链栈算法库
- 第6周项目2 建立栈链算法库
- 第6周项目2建立链栈算法库
- 【第6周 项目2 - 建立链栈算法库】
- 第6周 项目1 - 建立链栈算法库
- 百度地图定位demo
- 希尔排序
- pycharm调整字母长度分割线为80
- C---练习题部分2
- opencv里关于开启摄像头的一点心得
- 【栈项目2 - 建立链栈算法库--第6周】
- 【翻译】如何选择一个开源软件许可证 Choosing an OSS license doesn’t need to be scary
- kvo_and_kvc
- ubuntu 安装virtual-box
- Mahout 对推荐数据的抽象表示(上部分)
- 冒泡排序的优化
- 软件开发(1):序言
- ICA(Independent Component Analysis)算法入门
- 安卓中<TextView/>的作用