链式栈
LinkStack.h
#ifndef __LINKSTACK_H__
#define __LINKSTACK_H__
#define elemnet int
typedef struct SNode
{
element data;
struct SNode *next;
struct SNode *prev;
}SNode;
typedef struct LinkStack
{
SNode *first;
SNode *top;
int Nodenum;
}LinkStack;
LinkStack *InitStack(void);
int push(LinkStack *s,element x);
int pop(LinkStack *s,element *e);
int GetTop(LinkStack* s, element *e);
void clearlinkstack(LinkStack *s);
void destroylinkstack(LinkStack *s);
int StackIsEmpty(LinkStack *s);
void printStack(LinkStack *S);
#endif
LinkStack.c
#include<stdio.h>
#include<stdlib.h>
#include"LinkStack.h"
LinkStack *InitStack(void)
{
LinkStack *l = malloc(sizeof(*l));
l->first = NULL;
l->top = NULL;
l->Nodenum = 0;
return l;
}
int push(LinkStack *s,element x)
{
if(s == NULL)
{
return 0;
}
SNode *p = malloc(sizeof(*p));
if(p == NULL)
{
return 0;
}
p->data = x;
p->next = p->prev = NULL;
if(s->top == NULL)
{
s->top = p;
s->first = p;
}
else
{
s->top->next = p;
p->prev = s->top;
s->top = p;
}
s->Nodenum++;
return 1;
}
int pop(LinkStack *s,element *e)
{
if(s == NULL || s->Nodenum == 0)
{
return 0;
}
*e = s->top->data;
SNode *px = s->top;
if(s->Nodenum == 0)
{
s->first = NULL;
s->top = NULL;
free(px);
}
else
{
s->top = px->prev;
px->prev->next = NULL;
px->prev = NULL;
free(px);
}
s->Nodenum--;
return 1;
}
int GetTop(LinkStack* s, element *e)
{
if (s == NULL || s->Nodenum == 0)
{
return 0;
}
*e = s->top->data;
printf("%d\n",*e);
return 1;
}
void clearlinkstack(LinkStack *s)
{
if(s == NULL || s->top == NULL)
{
return;
}
SNode *p = s->first;
while(p)
{
s->first = p->next;
if(p->next)
{
p->next->prev = NULL;
}
p->next = NULL;
free(p);
p = s->first;
}
s->top = NULL;
s->Nodenum = 0;
return;
}
void destroylinkstack(LinkStack *s)
{
if(s == NULL)
{
return;
}
clearlinkstack(s);
free(s);
}
int StackIsEmpty(LinkStack *s)
{
if (s == NULL || s->Nodenum == 0)
{
return 1;
}
return 0;
}
void printStack(LinkStack *S)
{
SNode *p = S->top;
while (p)
{
printf("%d ", p->data);
p = p->prev;
}
printf("\n");
}
main.c
#include<stdio.h>
#include<stdlib.h>
#include"LinkStack.h"
int main()
{
LinkStack *s = InitStack();
element x,e;
printf("请输入数据,以0结尾\n");
while(1)
{
scanf("%d",&x);
if(x == 0)
{
break;
}
push(s,x);
GetTop(s,&e);
}
printStack(s);
return 0;
}