第5周实践项目2 链栈的算法库建立
2017-09-28 21:26
302 查看
listack.h #ifndef LISTACK_H_INCLUDED #define LISTACK_H_INCLUDED 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); //输出栈中元素 #endif // LISTACK_H_INCLUDED listack.cpp
#include <stdio.h> #include <malloc.h> #include "listack.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); //s指向尾结点,释放其空间 } int StackLength(LiStack *s) //返回栈长度 { int i=0; LiStack *p; p=s->next; while (p!=NULL) { i++; p=p->next; } return(i); } 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; //p指向开始节点 e=p->data; s->next=p->next; //删除*p节点 free(p); //释放*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"); }
main.cpp #include <stdio.h> #include "listack.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; }
4000
相关文章推荐
- 第六周实践项目2--建立链栈的算法库
- 第5周实践项目1 顺序栈建立的算法库
- 第八周实践项目2—建立链串的算法库
- 第八周 数据结构实践项目——串 【项目1 - 建立顺序串的算法库
- 第六周项目2-建立链栈的算法库
- 第8周实践项目2 - 建立链串的算法库
- 第8周实践项目2 - 建立链串的算法库
- 第六周项目2—链栈的算法库建立
- 第8周实践项目1-建立顺序串的算法库
- 第八周实践项目~建立链串算法库
- 第八周项目实践2 建立连串算法库
- 第四周实践项目~建立“单链表”算法库
- 第八周实践项目~建立顺序串的算法库
- 第四周上机实践项目2——建立“单链表”算法库
- 第四周实践项目4 建立算法库——双链表
- 第8周实践项目2-建立链串的算法库
- 数据结构上机实践第八周项目2- 建立链串的算法库
- 第三周实践项目2-建立顺序表算法库
- 第八周 数据结构实践项目——串 【项目2 - 建立链串的算法库】
- 第八周上机实践项目1——建立顺序串的算法库