#include <stdio.h>
#include <stdlib.h>
#include "LinkStack.h"
LinkSatck InitSatck()
{
LinkStack ls=NULL;
return ls;
}
void DestoryStack(LinkSatck ls)
{
LinkSatck pre = ls, p;
if (pre == NULL)
return;
p = pre->next;
while (p != NULL)
{
free(pre);
pre = p;
p = p->next;
}
free(p);
}
int Push(LinkSatck ls, ElemType x)
{
LinkSatck p;
p = (LinkSatck )malloc(sizeof(StackNode));
p->data = x;
p->next = ls;
ls = p;
return 1;
}
int Pop(LinkSatck ls, ElemType *x)
{
LinkSatck p;
if (ls == NULL)
return 0;
p = ls; //p指向栈顶结点
*x = p->data;
ls = ls->next; //删除结点p
free(p);
return 1;
}
int GetTop(LinkSatck ls, ElemType *x)
{
if (ls == NULL)
return 0;
*x = ls->data;
return 1;
}
int StackEmpty(LinkSatck ls)
{
if (ls == NULL)
return 1;
return 0;
}
#ifndef _LINKSTACK_H_
#define _LINKSTACK_H_
typedef char ElemType;
//不带头结点
typedef struct node
{
ElemType data;
struct node *next;
}StackNode,*LinkSatck;
LinkSatck InitSatck();
void DestoryStack(LinkSatck ls);
int Push(LinkSatck ls, ElemType x);
int Pop(LinkSatck ls, ElemType *x);
int GetTop(LinkSatck ls, ElemType *x);
int StackEmpty(LinkSatck ls);
#endif
#include <stdio.h>
#include <stdlib.h>
#include "LinkStack.h"
int main()
{
ElemType e;
LinkSatck ls = InitSatck();
printf("初始化栈ls\n");
printf("栈%s\n", (StackEmpty(ls) == 1 ? "空" : "非空"));
printf("a进栈\n");
Push(ls, 'a');
printf("b进栈\n");
Push(ls, 'b');
printf("c进栈\n");
Push(ls, 'c');
printf("d进栈\n");
Push(ls, 'd');
printf("栈%s\n", (StackEmpty(ls) == 1 ? "空" : "非空"));
GetTop(ls, &e);
printf("栈顶元素:%c\n", e);
return 0;
}