链栈的进栈出栈操作

来源:互联网 发布:有没有淘宝卖家骗货 编辑:程序博客网 时间:2024/05/22 07:04
#include <stdio.h>
#include <stdlib.h>
#define OK 1
#define ERROR 0
typedef int ElemType;
typedef int Status;
typedef struct StackNode
{
ElemType data;
struct StackNode *next;


}Node;
typedef struct LinkStack
{
Node *top;
int length;
}LinkStack;


void IintStack(LinkStack *s)
{
s->top = NULL; 
s->length = 0;
printf("初始化链栈为空!\n");
}


void print( LinkStack s)
{
if (s.top == NULL)
{
printf("当前栈为空!\n");
return;
}
while(s.top != NULL)
{
printf("%d ",s.top->data);
s.top=s.top->next;
}
printf("\n");
}


Status Push(LinkStack *s,ElemType e)
{
Node *p=(Node *)malloc(sizeof(Node));
if (p == NULL)
{
printf("申请空间失败!\n");
return ERROR;
}
p->data = e;
p->next = s->top;
s->top = p;
s->length++;
return OK;
}


Status Pop(LinkStack *s,ElemType *e)
{
if (s->top == NULL)
{
printf("当前栈为空!\n");
return ERROR;
}
*e=s->top->data;
Node *L=s->top;
s->top = s->top->next;
free(L);
s->length--;
return OK;
}
void DestoryStack(LinkStack *s)
{
while(s->top != NULL)
{
Node *L=s->top;
s->top = s->top->next;
free(L);
}
}
int main()
{
LinkStack s1;
int i;
ElemType  e;
IintStack(&s1);
for ( i = 1; i <= 9; ++i)
{
Push(&s1,i);
}
print(s1);
Pop(&s1,&e);
print(s1);
DestoryStack(&s1);
print(s1);
return 0;
}