顺序实现:
#define InitSize 100
#define Increment 10
#define NUM 5
typedef int ElemType;
typedef struct{
ElemType *base;
ElemType *top;
int size;
}SqStack;
Status InitStack(SqStack &s)
{
s.base = (ElemType *)malloc(InitSize*sizeof(ElemType));
if(!s.base)
exit(OVERFLOW);
s.top = s.base;
s.size = InitSize;
return OK;
}
void DestoryStack(SqStack &s)
{
free(s.base);
}
void ClearStack(SqStack &s)
{
s.top = s.base;
}
Status StackEmpty(SqStack s)
{
if(s.top == s.base)
return TRUE;
else
return FALSE;
}
int StackLength(SqStack s)
{
int i = 0;
ElemType *p;
p = s.top;
while(p!=s.base)
{
p--;
i++;
}
return i;
}
Status Push(SqStack &s,ElemType e)
{
if(s.top-s.base >= s.size)
{
s.base = (ElemType *)realloc(s.base,(s.size + Increment)*sizeof(ElemType));
if(!s.base)
exit(OVERFLOW);
s.top = s.base + s.size;
s.size += Increment;
}
*s.top++ = e;
return OK;
}
Status Pop(SqStack &s,ElemType &e)
{
if(s.top == s.base)
return ERROR;
e = *(--s.top);
return OK;
}
Status GetTop(SqStack s,ElemType &e)
{
if(s.top == s.base)
return ERROR;
e = *(s.top - 1);
return OK;
}
void display(SqStack s)
{
ElemType e;
if(s.top == s.base)
cout<<"该栈为空栈。";
else
while(s.top != s.base)
{
Pop(s,e);
//ends:终止字符串 endl:终止一行并刷新缓冲区
cout<<e<<ends;
}
cout<<endl;
}
int main(int argc, char* argv[])
{
ElemType e,TopElem;
SqStack s;
InitStack(s);
for(int i=0 ; i<NUM ; i++)
{
cout<<"\n请输入第"<<i+1<<"个元素:";
cin>>e;
Push(s,e);
}
display(s);
GetTop(s,TopElem);
cout<<"TopElem="<<TopElem<<" "<<"length="<<StackLength(s)<<endl;
Pop(s,e);
cout<<"length="<<StackLength(s)<<endl;
return 0;
}