顺序栈-简单的实现

#include "stdafx.h"
// DataStack0106.cpp : 定义控制台应用程序的入口点。
#include"malloc.h"
#include"iostream"
using namespace std;
#define STACK_INIT_SIZE 100
typedef int ElemType;
typedef struct
{
ElemType *base;
ElemType * top;
int stacksize;
}SqStack;
//初始化
int InitStack(SqStack &S)
{
S.base = new ElemType[STACK_INIT_SIZE];
if (!S.base)
{
cout << "动态分配内存出错!" << endl;
exit(-1);
}
S.top = S.base;
S.stacksize = STACK_INIT_SIZE;

return 0;
}
//得到栈顶元素
int GetTop(SqStack S, ElemType &val)
{
if (S.top == S.base)
return 0;
val = *(S.top - 1);
return 1;
}
int PushStack(SqStack &S, ElemType val)
{
if (S.top - S.base >= S.stacksize)
{
S.base = new ElemType[S.stacksize + STACK_INIT_SIZE];
if (!S.base) return 0;
S.top = S.base + S.stacksize;
S.stacksize += STACK_INIT_SIZE;
}
*(S.top++) = val;
return 1;
}
//出栈
int PopStack(SqStack &S, ElemType &val)
{
if (S.top == S.base)return 0;
//--S.top;
val = *--S.top;
return 1;
}
//遍历
void TrasverStack(SqStack S)
{
int i;
if (S.top == S.base)
cout << "空栈" << endl;
for (i = S.top - S.base; i > 0; i--)
cout << S.base[i - 1] << endl;
}
int lengthStack(SqStack &S)
{
return S.top - S.base;
}

int _tmain(int argc, _TCHAR* argv[])
{
ElemType val;
SqStack S;
InitStack(S);
PushStack(S, 1);
PushStack(S, 2);
PushStack(S, 3);
PushStack(S, 4);
cout << "出栈 " << endl;
TrasverStack(S);
cout << "栈顶元素为 " << endl;
GetTop(S, val);
cout << "出栈元素 " << endl;
PopStack(S, val);
cout << "栈的长度为 " << endl;
lengthStack(S);
return 0;
}

我是真的不知道为啥gettop和popStack()这2个函数为啥不实现功能呢

函数功能没问题 不过你的调用和你的打印描述对不上 而且你没有打印任何的数值出来

把main中的内容修改成这样 


ElemType val;
SqStack S;
InitStack(S);
PushStack(S, 1);
PushStack(S, 2);
PushStack(S, 3);
PushStack(S, 4);
TrasverStack(S);
GetTop(S, val);
cout << "栈顶元素为 " << val << endl;
cout << "出栈 " << endl;
PopStack(S, val);
cout << "出栈元素 " << val << endl;
cout << "栈的长度为 " << lengthStack(S) <<endl;

return 0;
温馨提示:答案为网友推荐,仅供参考
相似回答