您的位置:首页 > 其它

ADT - 栈(Stack)

2017-09-25 16:34 239 查看
仅供参考,正确性有待检查(QAQ)
/ADT SqStack
#include<iostream>

#define		TRUE			1
#define		FALSE			0
#define		OK				1
#define		ERROR			0
#define		OVERFLOW		-1
#define		INITLENGTH		100
#define		INCREASESIZE	10

using namespace std;
typedef int SElemType;
typedef int Status;

typedef struct {
SElemType *base;//栈底地址
SElemType *top;//栈顶地址
int stacksize;//栈容量
}SqStack;

//初始化空栈
Status InitStack(SqStack &S) {
S.base = (SElemType *)malloc(sizeof(SElemType) * INITLENGTH);
if (!S.base)exit(OVERFLOW);
S.top = S.base;
S.stacksize = INITLENGTH;
return OK;
}

//清空栈
Status ClearStack(SqStack &S) {
S.top = S.base;
return OK;
}

//销毁栈
Status DestroyStack(SqStack& S) {
free(S.base);
S.top = S.base = NULL;
S.stacksize = 0;
return OK;
}

//栈扩容
void IncStackSize(SqStack &S) {
S.base = (SElemType *)realloc(S.base, sizeof(SElemType)*(S.stacksize + INCREASESIZE));
S.stacksize += INCREASESIZE;
}

//压栈
Status Push(SqStack &S, SElemType e) {
if (S.stacksize == S.top - S.base)
IncStackSize(S);
*(S.top++) = e;
return OK;
}

//出栈
Status Pop(SqStack &S, SElemType &e) {
if (S.top == S.base) return ERROR;
e = *(--S.top);
return OK;
}

//判栈空
Status IsEmpty(SqStack &S) {
return S.top == S.base ? TRUE : FALSE;
}

//返回栈深
int StackLength(SqStack &S) {
return S.top - S.base;
}

//获取栈顶元素
Status GetTop(SqStack &S, SElemType &e) {
if (S.top == S.base)return ERROR;
e = *(S.top - 1);
return OK;
}

//栈元素遍历输出
Status StackPrint(SqStack &S) {
if (S.top == S.base)return ERROR;
SElemType *curPtr;
curPtr = S.base;
while(curPtr < S.top) {
if (curPtr == S.base)cout << *(curPtr);
else cout << ' ' << *(curPtr);
curPtr++;
}
cout << endl;
return OK;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  adt