#include <stdlib.h>
#include <stdio.h>
#define FALSE 0
#define TRUE 1
typedef int StackData;
typedef struct _node
{
StackData data;
struct _node *next;
}Node;
typedef struct _linkStack
{
Node *top;
}LinkStack;
// 建栈
LinkStack *Create_Stack()
{
LinkStack* s = (LinkStack*)malloc(sizeof(LinkStack)/sizeof(char));
if (s == NULL)
{
errno = MALLOC_ERROR;
return NULL;
}
// 置空栈
s->top = NULL;
return s;
}
// 判断空栈
int StackEmpty (LinkStack *s)
{
if (s == NULL)
{
errno = ERROR;
return FALSE;
}
return s->top == NULL;
}
// 进栈
int Push (LinkStack *s, StackData x)
{
if (s == NULL)
{
errno = ERROR;
return FALSE;
}
// 新建结点
Node* node = (Node*)malloc(sizeof(Node)/sizeof(char));
if (node == NULL)
{
errno = MALLOC_ERROR;
return FALSE;
}
node->data = x;
node->next = s->top;
s->top = node;
return TRUE;
}
// 出栈
int Pop (LinkStack *s, StackData *x)
{
if (s == NULL)
{
errno = ERROR;
return FALSE;
}
if (StackEmpty(s))
{
errno = EMPTY_STACK;
return FALSE;
}
Node *p = s->top;
*x = p->data;
s->top = p->next;
free(p);
return TRUE;
}
// 获取栈顶元素
int GetTop (LinkStack *s, StackData *x)
{
if (s == NULL)
{
errno = ERROR;
return FALSE;
}
if (StackEmpty(s))
{
errno = EMPTY_STACK;
return FALSE;
}
*x = s->top->data;
return TRUE;
}
// 销毁栈
int Destroy(LinkStack *s)
{
if (s == NULL)
{
errno = ERROR;
return FALSE;
}
int x;
while(StackEmpty(s) != TRUE)
{
Pop (s, &x);
}
free(s);
return TRUE;
}
干货4:链式栈
最新推荐文章于 2024-07-29 18:04:33 发布