//stack.h
#include<stdio.h>
#include<stdlib.h>
#define TRUE 1
#define FALSE 0
#define OK 1
#define ERROR 0
#define OVERFLOW -1
#define UNDERFLOW -2
typedef int Status;
typedef int ElemType;
struct LNode{
ElemType data; //数据域
struct LNode *next; //指针域
};
struct LStack{
struct LNode *top; //栈顶指针
};
Status InitStack(LStack &s){
struct LNode *p;
p=(LNode *)malloc(sizeof(LNode));
if(!p)
exit(ERROR);
s.top=p;
p->next=NULL;
return OK;
}
Status DestroyStack(LStack &s){
struct LNode *p;
p=s.top;
while(p){
s.top=p->next;
free(p);
p=s.top;
}
return OK;
}
Status StackEmpty(LStack s){
if(s.top->next==NULL)
return TRUE;
return FALSE;
}
Status StackLength(LStack s){
int length=0;
struct LNode *p;
p=s.top;
while(p->next){
length++;
p=p->next;
}
return length;
}
Status Push(LStack &s,ElemType e){
struct LNode *p;
p=(LNode *)malloc(sizeof(LNode));
if(!p)
exit(OVERFLOW);
s.top->data=e;
p->next=s.top;
s.top=p;
return OK;
}
Status Pop(LStack &s,ElemType &e){
struct LNode *p;
if(!(s.top->next))//判断栈是否为空·
exit(UNDERFLOW);
p=s.top;
s.top=p->next;
e=s.top->data;
free(p);
return OK;
}
Status GetTop(LStack s,ElemType &e){
if(!(s.top->next))
exit(ERROR);
s.top=s.top->next;
e=s.top->data;
return OK;
}
Status StackTraverse(LStack s){
//从栈顶开始依次输出
struct LNode *p;
if(!(s.top->next))
exit(ERROR);
p=s.top;
while(p->next){
p=p->next;
printf("%d\n",p->data);
}
return OK;
}
int main(){
int e;
struct LStack s;
InitStack(s);
Push(s,4);
GetTop(s,e);
printf("%d\n",e);
printf("%d\n",StackLength(s));
Pop(s,e);
printf("%d\n",StackEmpty(s));
StackTraverse(s);
return 0;
}