代码完成了下列算法
- Initstack
- Push
- Pop
- Isfull
- Isempty
其实堆栈有两种表达方法
- top指向栈顶元素
- top指向栈顶元素的后一位
此代码使用的是前者
#include<iostream>
using namespace std;
typedef int ElementType;
#define maxsize 10
typedef struct snode* Stack;
struct snode{
ElementType data[maxsize];
int top;
};
Stack Initstack()
{
Stack ptrs;
ptrs = ( Stack )malloc( sizeof(struct snode) );
ptrs->top = -1;
return ptrs;
}
bool Isfull( Stack ptrs )
{
if( ptrs->top==maxsize-1 )
return true;
else
return false;
}
bool Isempty( Stack ptrs )
{
if( ptrs->top==-1 )
return true;
else
return false;
}
void Push ( Stack ptrs, ElementType x )
{
if( ptrs->top == maxsize-1 ){
cout<<"堆栈满"<<endl;
return;
}else{
ptrs->data[ ++(ptrs->top) ]= x;
return;
}
}
ElementType Pop( Stack ptrs )
{
if( ptrs->top==-1 ){
cout<<"堆栈空"<<endl;
return NULL;
}else{
return ptrs->data[ ptrs->top-- ];
}
}
int main()
{
Stack ptrs;
ptrs = Initstack();
bool x = Isempty(ptrs);
cout<<x<<endl;
Push( ptrs, 1);
Push( ptrs, 3);
Push( ptrs, 5);
cout<<Pop( ptrs )<<endl;
x = Isfull(ptrs);
cout<<x<<endl;
return 0;
}
运行结果