#include<stdio.h>
#include<stdlib.h>
#include <malloc.h>
#include <iostream.h>
#define Status int
#define STACK_INIT_SIZE 100
#define ERROR 0
#define OK 1
#define TRUE 1
#define FALSE 0
typedef struct{
int *base,*top;
int stackSize;
}Stack;
//初始化栈
Status initStack(Stack &s){
s.base = (int *)malloc(STACK_INIT_SIZE*(sizeof(int)));
if (!s.base)
return ERROR;
else
s.top = s.base;
s.stackSize = STACK_INIT_SIZE;
}
Status destoryStack(Stack &s){//销毁栈
s.top = s.base;
free(s.base);
s.base = NULL;
s.top = NULL;
return OK;
}
bool isEmpty(Stack s){
if (s.base == s.top)
return TRUE;
else
return FALSE;
}
int stackLenght(Stack s){//栈中元素个数
if (s.base == s.top)
return ERROR;
else
return s.top - s.base;
}
int getTop(Stack s){//获取栈顶元素
if (s.base == s.top){
cout << "stack is empty" << endl;
return 0;
}
else{
s.top--;
return *s.top;
}
}
Status push(Stack &s,int e){//元素入栈
if (stackLenght(s) == STACK_INIT_SIZE){
cout << "stack is full" << endl;
return ERROR;
}
else{
*(s.top) = e;
s.top++;
return OK;
}
}
int pop(Stack &s){//元素出栈
if (isEmpty(s)){
cout << "stack if empty" << endl;
return 0;
}
else{
s.top--;
return *(s.top);
}
}
Status clearStack(Stack &s){//置空栈
s.top = s.base;
s.stackSize = 0;
return OK;
}
void displayStack(Stack s){//打印栈
if (isEmpty(s))
exit(-1);
else{
while (s.top != s.base){
--s.top;
cout << *(s.top) << endl;
}
}
}
int main(int argc, char* argv[])
{
Stack s;
initStack(s);
for (int i = 0; i < 5; i++){
if (push(s, i))
cout << i << "is push in stack successful!" << endl;
else
cout << "there is a error" << endl;
}
displayStack(s);
int top = getTop(s);
cout << top << endl;
return 0;
}
出现的问题:
开始时栈的定义前没有用typedef,后面的函数对栈的引用都会出现问题。