链栈的设计与实现

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

实验指导三 链栈的设计与实现

一.任务分析

链表栈的基本操作包括栈的建立、求长度、取栈顶元素、入栈、出栈、判断栈是否空等具体操作。
二.程序构思

栈的链式存储结构称为链栈,即用链表来存储栈。由于栈的操作是受限的,出栈与进栈都是在表的一端进行,因此程序就是实现特殊的链表操作。

三.源程序

// 调试环境:Visual C++6.0
// 库文件和预设定义
#include
#include
#define Stack_Length 6
#define OK 1
#define ERROR 0
typedef int SElemType;
typedef struct SNode
{
SElemType data;
struct SNode *next;
}SNode,*LinkStack;
/****-------------------------------------------- *****/
// 函数名:CreateTwo(LNode* head, int n)
// 参数:(传入)LNode* head传入一个链表指针
// (传入)int n,传入线性表结点数量
// (传出)ElemType &e存储删除结点元素的值
// 作用:建立一个空栈
// 返回值:无
/****-------------------------------------------- *****/
void CreateTwo(LinkStack &head, int n)
{
int i;
SNode *p;/* 定义新结点指针 */
/* 建立带头结点的线性链表 */
head=(LinkStack)malloc(sizeof(SNode));
head->next=NULL;
printf("Please input the data for LinkList Nodes: \n");
for(i=n;i>0;--i)
{
p=(SNode*)malloc(sizeof(SNode));
/* 为新结点申请空间,即创建一新结点 */
scanf("%d",&p->data); /* 新结点赋值 */
/* 新结点插入到表头 */
p->next=head->next;
head->next=p;
}
}
/****-------------------------------------------- *****/
// 函数名: Push(LinkStack &top,SElemType e)
// 参数:(传入)LinkStack &top,栈顶指针
// (传入)SElemType e入栈元素
// 作用:入栈
// 返回值:int 型返回1表示入栈成功,0表示失败
/****-------------------------------------------- *****/
int Push(LinkStack &top,SElemType e)
{
SNode *q;
q=(LinkStack)malloc(sizeof(SNode));/* 创建入栈元素结点 */
/* 创建结点失败处理 */
if(!q)
{
printf("Overfolow !\n");
return (ERROR);
}
q->data=e;
q->next=top->next;/* 入栈元素结点插入栈顶 */
top->next=q;
return (OK);
}
/****-------------------------------------------- *****/
// 函数名:Pop(LinkStack &top,SElemType &e)
// 参数:(传入)LinkStack &top,栈顶指针
// (传出)SElemType e出栈元素
// 作用:出栈
// 返回值:int型返回1表示出栈成功,0表示失败
/****-------------------------------------------- *****/
int Pop(LinkStack &top,SElemType &e)
{
SNode *q;/* 定义

临时存储栈顶结点的指针 */
if(!top->next)
{
printf("error");
return (ERROR);
}
e=top->next->data;
q=top->next;
top->next=q->next;/* 删除栈顶元素 */
free(q);
return (OK);
}
//------------------- 测试程序 ---------------------
void main()
{
int e;
/* 建立一个栈 */
LinkStack top;
/* 使用建立方法二 */
CreateTwo(top, 3);
/* 显示栈元素 */
LinkStack p;
printf("\nThe old LinkStack is (top to bottom) : \n");
p=top;
while(p->next)
{
p=p->next;
printf("%d ", p->data);
}
printf("\nPlease input the data to push : ");
scanf("%d", &e);
/* 入栈操作 */
if(Push(top,e))
printf("success to push");
/* 显示栈元素 验证入栈操作成功否 */
printf("\nThe new LinkStack is : \n");
while(top->next)
{
top=top->next;
printf("%d",top->data);
}
}



相关文档
最新文档