#ifndef __LISTSTACK_H__
#define __LISTSTACK_H__
#include "error.h"
#define TRUE 1
#define FLASE 0
#define SIZE 100
typedef struct _sqstack
{
int data;
struct _sqstack *next;
}StackNode;
typedef struct _liststack
{
StackNode *top;
}LinkStack;
//创建头节点
LinkStack *creat_list();
//进栈
int push (LinkStack *s, int x);
//判断空栈
int StackEmpty(LinkStack *s);
//出栈
int Pop (LinkStack *s, int *x);
//取栈顶元素
int GetTop (LinkStack *s, int *x);
//销毁栈
void Distroy(LinkStack *s,int *x);
#endif //__LISTSTACK_H__
#ifndef __ERROR_H__#define __ERROR_H__#include <stdio.h>#define ERROR -1#define FULL_STACK -2#define EMPTY_STACK -3int errno;void myerror(char *str);char *mysrterror (int num);#endif //__ERROR_H__
#include "error.h"
void myerror(char *str)
{
switch(errno)
{
case ERROR:
printf("%s:输入参数错误\n",str);
break;
case FULL_STACK:
printf("%s:满栈\n",str);
break;
case EMPTY_STACK:
printf("%s:空栈\n",str);
break;
}
}
char *mysrterror(int num)
{
switch(errno)
{
case ERROR:
return "输入参数错误";
case FULL_STACK:
return "满栈";
case EMPTY_STACK:
return "空栈";
}
}
#include "liststack.h"
#include <stdlib.h>
LinkStack *creat_list()
{
LinkStack *s = (LinkStack *)malloc(sizeof(LinkStack)/sizeof(char));
if(s == NULL)
{
errno = ERROR;
return NULL;
}
return s;
}
int StackEmpty(LinkStack *s)
{
if(s == NULL)
{
errno = ERROR;
return FLASE;
}
return s->top == NULL;
}
int push (LinkStack *s, int x)
{
if(s == NULL)
{
errno = ERROR;
return FLASE;
}
StackNode *node = (StackNode *)malloc(sizeof(StackNode)/sizeof(char));
if(node == NULL)
{
errno = ERROR;
return FLASE;
}
node->data = x;
node->next = s->top;
s->top = node;
return TRUE;
}
int Pop (LinkStack *s, int *x)
{
if(s == NULL)
{
errno = ERROR;
return FLASE;
}
if(StackEmpty(s))
{
errno = EMPTY_STACK;
return FLASE;
}
StackNode *p = s->top;
*x = p->data;
s->top = p->next;
free(p);
return TRUE;
}
int GetTop (LinkStack *s, int *x)
{
if(s == NULL)
{
errno = ERROR;
return FLASE;
}
if(StackEmpty(s))
{
errno = EMPTY_STACK;
return FLASE;
}
*x = s->top->data;
return TRUE;
}
void Distroy(LinkStack *s,int *x)
{
if(s == NULL)
{
errno = ERROR;
return ;
}
if(StackEmpty(s))
{
errno = EMPTY_STACK;
return ;
}
while(!StackEmpty(s))
{
Pop (s, x);
}
free(s);
}
#include <stdio.h>
#include "liststack.h"
int main()
{
LinkStack *s = creat_list();
int x;
if(StackEmpty(s))
{
printf("空栈\n");
}
int i;
for(i = 0; i < 10; i++)
{
push(s, i);
}
if(push(s, 100) != TRUE)
{
myerror("压入第11个元素");
}
char str[100];
for(i = 0;i < 12; i++)
{
if(Pop (s, &x) != TRUE)
{
sprintf (str,"Pop第%d个元素",i);
myerror (str);
}
printf("x = %d\n",x);
}
return 0;
}