http://blog.csdn.net/sxhelijian/article/details/48463801
本文针对数据结构基础系列网络课程(3):栈和队列中第4课时栈的链式存储结构及其基本运算实现。
按照“0207将算法变程序”[视频]部分建议的方法,建设自己的专业基础设施算法库。
链栈算法库采用程序的多文件组织形式,包括两个文件:
1.头文件:listack.h,包含定义链栈数据结构的代码、宏定义、要实现算法的函数的声明;
#ifndef LISTACK_H_INCLUDED
#define LISTACK_H_INCLUDEDtypedef 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
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
2.源文件: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对应的节点*pp->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");
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
- 65
- 66
- 67
- 68
- 69
- 70
- 71
- 72
- 73
- 74
- 75
- 76
- 77
- 78
- 79
- 80
3.在同一项目(project)中建立一个源文件(如main.cpp),编制main函数,完成相关的测试工作。 例:
#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;
}