五.链式栈结构的实现程序

来源:互联网 发布:培训机构的程序员 编辑:程序博客网 时间:2024/06/06 07:07

并实现了链式栈的基本操作,例如:初始化、销毁、判空、获取长度,插入、删除、获取栈顶元素,遍历。

(一)该头文件定义了链式栈的存储结构(带头节点),对链式栈的基本操作的函数原型进行了声明(linkStack.h)。

#pragma once //保证头文件被编译一次

//定义函数结果状态代码  #define TRUE        1  #define FALSE       0  #define OK          1  #define ERROR       0  #define OVERFLOW    -1  #define UNDERFLOW   -2   //定义函数返回值类型  typedef int  Status;  //定义链式栈的数据元素的类型  typedef int  ElemType;//定义链式栈的存储结构  struct LNode{ ElemType data;  //数据域 struct LNode *next;    //指针域};struct LStack{      struct LNode    *top;       //栈顶指针   };//声明链式栈的基本操作  Status  InitStack(LStack &s);  Status  DestroyStack(LStack &s);   Status  StackEmpty(LStack s);  Status  StackLength(LStack s);  Status  Push(LStack &s,ElemType e);  Status  Pop(LStack &s,ElemType &e);  Status  GetTop(LStack s,ElemType &e);  Status  StackTraverse(LStack s);(二)该源文件实现了头文件声明的函数(linkStack.cpp)#include"linkStack.h"#include<iostream>using namespace std;Status  InitStack(LStack &s)//操作结果:构造一个空栈S{   struct LNode *p;   p=(LNode *)malloc(sizeof(LNode));   if(!p){        cout<<"严重错误:链式栈初始分配头节点失败,程序退出";          exit(ERROR);    }   s.top=p;   p->next=NULL;   return OK;  } Status  DestroyStack(LStack &s)   //初始条件:栈s已存在   //操作结果:栈s被销毁  {      struct LNode *p;    p=s.top;    while(p){        s.top=p->next;        free(p);        p=s.top;    }        return OK;  }  Status  StackEmpty(LStack s)//初始条件:栈s已存在  //操作结果:若栈s为空栈,则返回TRUE,否则FALSE {   if(s.top->next==NULL) return TRUE;   return FALSE; }Status  StackLength(LStack s)//初始条件:栈s已存在  //操作结果:返回s的元素个数,即栈的长度{   int length=0;   struct LNode *p;   p=s.top;   while(p->next){   length++;   p=p->next;   }   return length;} Status Push(LStack &s,ElemType e)//初始条件:栈s已存在  //操作结果:插入元素e成为新的栈顶元素{     struct LNode *p;   p=(LNode *)malloc(sizeof(LNode));   if(!p)exit(OVERFLOW);   s.top->data=e;   p->next=s.top;   s.top=p;   return OK;}   Status  Pop(LStack &s,ElemType &e) //初始条件:栈s已存在且非空   //操作结果:删除s的栈顶元素,并且用e返回其值 {    struct LNode *p;    if(!(s.top->next))exit(UNDERFLOW);    p=s.top;    s.top=p->next;    e=s.top->data;    free(p);    return OK; }Status  GetTop(LStack s,ElemType &e) //初始条件:栈s已存在且非空  //操作结果:用e返回s的栈顶元素 {     if(!(s.top->next))exit(ERROR);     s.top=s.top->next;     e=s.top->data;     return OK;} Status  StackTraverse(LStack s)//从栈顶开始依次输出{     struct LNode *p;     if(!(s.top->next))exit(ERROR);     p=s.top;     while(p->next){     p=p->next;     cout<<p->data<<endl;     }     return OK;}(三)该源文件为测试程序(demo.cpp)#include"linkStack.h"#include<iostream>using namespace std;int main(){ int e; struct LStack s; InitStack(s); Push(s,4); GetTop(s,e); cout<<e<<endl; Push(s,5); Push(s,6); Push(s,7); Push(s,8); Push(s,9); GetTop(s,e); cout<<e<<endl; cout<<StackLength(s)<<endl; Pop(s,e); Pop(s,e); Pop(s,e); Pop(s,e); cout<<StackEmpty(s)<<endl; StackTraverse(s);}


原创粉丝点击