您的位置:首页 > 理论基础 > 数据结构算法

数据结构(3):顺序栈的表示和实现

2016-03-21 23:19 375 查看
/*  语言:C++                  编译环境:Visual C++6.0
顺序栈的表示和实现
*/
#include <iostream>
#define OK 1
#define ERROR 0
#define OVERFLOW -2
#define MAXSIZE 100
// Status是函数返回值类型,其值是函数结果状态代码
typedef int Status;
// 自定义数据类型别名
typedef int ElemType;
using namespace std;

// 顺序栈的存储结构
typedef struct
{
ElemType *base; // 栈底指针
ElemType *top;  // 栈顶指针
int stacksize;  // 栈可用的最大容量
}SqStack;

// 栈的初始化
Status InitStack(SqStack &S)
{   // 构造一个空栈
// 为顺序栈动态分配一个最大容量为MAXSIZE的数组空间
S.base = new ElemType[MAXSIZE];
if(!S.base) exit(OVERFLOW);     // 存储分配失败
S.top = S.base;                 // top初始为base,空栈
S.stacksize = MAXSIZE;      // stacksize置为栈的最大容量MAXSIZE
return OK;
}

// 顺序栈的入栈
Status Push(SqStack &S, ElemType e)
{   // 插入元素e为新的栈顶元素
// 栈满(S.top的地址值与S.base的地址值之差为顺序栈的长度)
if(S.top-S.base == MAXSIZE) return ERROR;
*S.top++ = e;                   // 元素e压入栈顶,栈顶指针加1
return OK;
}

// 顺序栈的出栈
Status Pop(SqStack &S, ElemType &e)
{   // 删除S的栈顶元素,用e返回其值
if(S.top == S.base) return ERROR;   // 栈空
e = *--S.top;                   // 栈顶指针减1,将栈顶元素赋给e
return OK;
}

// 取顺序栈的栈顶元素
ElemType GetTop(SqStack S)
{   // 返回S的栈顶元素,不修改栈顶指针
if(S.top != S.base)     // 栈非空
return *(S.top-1);  // 返回栈顶元素的值,栈顶指针不变
return ERROR;
}

int main()
{
SqStack S;
// 列表菜单
cout<<"1 InitStack"<<endl;
cout<<"2 Push"<<endl;
cout<<"3 Pop"<<endl;
cout<<"4 GetTop"<<endl;

int choice,e;
while(1)
{
cout<<"Input a choice: ";
cin>>choice;

// 选择
switch(choice)
{
case 1:
InitStack(S);
continue;
case 2:
Push(S,3);
continue;
case 3:
Pop(S,e);
continue;
case 4:
cout<<"Get: "<<GetTop(S)<<endl;
continue;
default:
cout<<"End..."<<endl;
break;
}
break;
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  C++