#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
#define OK 1
#define ERROR 0
#define OVERFLOW -2
#define STACK_INIT_SIZE 100
#define STACKINCREMENT 10
typedef int SElemType ;
typedef int Status ;
typedef struct SNode
{
SElemType data ;
struct SNode *next;
}SNode ;
typedef struct
{
SNode *top ;
}Stack;
Status InitStack(Stack &s);
Status DestoryStack(Stack &s);
Status ClearStack(Stack &s);
Status StackEmpty(Stack s);
int StackLength(Stack s);
Status GetTop(Stack s, SElemType &e);
Status Push(Stack &s, SElemType e);
Status Pop(Stack &s , SElemType &e);
Status StackTraverse(Stack s, Status(*visit)());
void Display(Stack s);
Status InitStack(Stack &s)
{
s.top=(SNode*)malloc(sizeof(SNode));
if(!s.top)
return ERROR ;
s.top->next=NULL;
return OK;
}
Status ClearStack(Stack &s)
{
SNode *pNode, *temp;
pNode=s.top->next;
while(pNode!=NULL)
{
temp=pNode;
pNode =pNode->next;
free(temp);
}
return OK;
}
Status DestoryStack(Stack &s)
{
ClearStack(s);
free(s.top);
return OK;
}
Status StackEmpty(Stack s)
{
if(s.top->next==NULL)
return OK ;
else
return ERROR;
}
int StackLength(Stack s)
{
int length=0;
SNode *pNode;
pNode = s.top->next;
while(pNode)
{
length++;
pNode =pNode->next;
}
return length ;
}
Status GetTop(Stack s, SElemType &e)
{
if(s.top->next!=NULL)
{
e= s.top->next->data;
return OK;
}
return NULL;
}
Status Push(Stack &s, SElemType e)
{
SNode *p;
p=(SNode *)malloc(sizeof(SNode));
if(!p)
return ERROR;
p->data=e;
p->next=s.top->next;
s.top->next=p;
return OK ;
}
Status Pop(Stack &s , SElemType &e)
{
if(s.top->next==NULL)
return ERROR;
SNode *p;
p=s.top->next;
e = p->data;
s.top->next=p->next;
free(p);
return OK;
}
Status StackTraverse(Stack s, Status(*visit)(SElemType data))
{
SNode *p ;
p=s.top->next;
while(p)
{
visit(p->data);
p=p->next;
}
return OK;
}
Status visit(SElemType data)
{
printf("%d",data);
return OK;
}
void Display(Stack s)
{
SNode *p ;
p=s.top->next;
while(p)
{
printf("%d\t",p->data);
p=p->next;
}
printf("\n");
}
int main()
{
Stack s ;
printf("init stack begin....\n");
if(InitStack(s))
printf("初始化成功\n");
printf("初始栈为空 = %d \n" , StackEmpty(s));
printf("初始化时栈的长度= %d\n",StackLength(s));
printf("init stack end. \n");
printf("push element into stack begin.... :\n ");
for(int i=0;i<5;i++)
{
Push(s,i);
}
printf("入栈后不为空 = %d \n" , StackEmpty(s));
printf("入栈的后长度=%d\n",StackLength(s));
Display(s);
printf("push elements into stack end.\n");
int e ;
Pop(s,e);
printf("出栈的元素为= %d\n", e);
printf("after Pop......\n");
printf("出栈的后长度= %d\n",StackLength(s));
Display(s);
int f ;
GetTop(s,f);
printf("栈顶元素为= %d\n", f);
Display(s);
ClearStack(s);
printf("栈已清空\n");
}