C语言实现栈的链式存储结构
#include <stdio.h>
#include <stdlib.h>
typedef int ElemType;
typedef int Statue;
#define ERROR 0
#define SUCCESS 1
#define OVER 0
#define EMPTY 0
#define NOT_EMPTY 1
typedef struct StackNode
{
ElemType data;
struct StackNode *next;
} StackNode, *LinkStackPtr;
typedef struct LinkStack
{
LinkStackPtr top;
int count;
} linkStack, *LinkStack;
Statue InitStack(LinkStack *L);
Statue push(LinkStack L, ElemType e);
Statue pull(LinkStack L, ElemType *e);
int isEmpty(LinkStack L);
Statue showStack(LinkStack L);
int main(void)
{
LinkStack linkStack;
int i;
ElemType data;
InitStack(&linkStack);
isEmpty(linkStack);
for (i = 0; i < 6; i++)
{
push(linkStack, i);
}
showStack(linkStack);
int count = linkStack->count;
printf("出栈顺序是:");
for(i = 0; i < count; i++){
pull(linkStack, &data);
printf("%4d", data);
}
printf("\n");
isEmpty(linkStack);
printf("\n\n");
return 0;
}
int isEmpty(LinkStack L)
{
if (L->count == 0)
{
printf("栈为空\n");
return EMPTY;
}
else
{
printf("栈为不空\n");
return NOT_EMPTY;
}
}
Statue InitStack(LinkStack *L)
{
(*L) = (LinkStack)malloc(sizeof(linkStack));
if ((*L) == NULL)
{
printf("栈内存分配错误\n\n");
exit(ERROR);
}
printf("栈内存分配成功\n\n");
(*L)->top = NULL;
(*L)->count = 0;
return SUCCESS;
}
Statue push(LinkStack L, ElemType e)
{
LinkStackPtr pushNode = (LinkStackPtr)malloc(sizeof(StackNode));
if (pushNode == NULL)
{
printf("入栈结点内存分配失败!\n\n");
return ERROR;
}
pushNode->data = e;
pushNode->next = L->top;
L->top = pushNode;
++L->count;
return SUCCESS;
}
Statue pull(LinkStack L, ElemType *e)
{
if(!(L->count)){
return ERROR;
}
LinkStackPtr node = L->top;
*e = node->data;
L->top = node->next;
free(node);
--L->count;
return SUCCESS;
}
Statue showStack(LinkStack L)
{
LinkStackPtr showNode;
if (!isEmpty(L))
{
return EMPTY;
}
showNode = L->top;
printf("栈内数据为:");
do
{
printf("%4d", showNode->data);
showNode = showNode->next;
} while (showNode->next != NULL);
printf("%4d", showNode->data);
printf("\n\n");
return SUCCESS;
}