#include <stdio.h>
#include <malloc.h>
#include <stdlib.h>
#define OK 0
#define ERROR -1
#define ElemType int
//定义栈的结点的结构
typedef struct Node
{
ElemType data;
Node *next;
}Node;
//定义栈的结构
typedef struct Stack
{
Node *top; //栈顶指针
Node *bottom; //栈底指针
}Stack;
//初始化一个栈
int initStack(Stack *pStack);
//压栈
void pushStack(Stack *pStack, ElemType e);
//出栈
int popStack(Stack *pStack, ElemType *e);
//清空栈
void clearStack(Stack *pStack);
//遍历输出整个栈
void traverse(Stack *pStack);
int main()
{
Stack stack;
initStack(&stack);
int e;
pushStack(&stack, 1);
pushStack(&stack, 2);
pushStack(&stack, 3);
pushStack(&stack, 4);
pushStack(&stack, 5);
traverse(&stack);
popStack(&stack, &e);
popStack(&stack, &e);
printf("pop:%d\n", e);
clearStack(&stack);
popStack(&stack, &e);
traverse(&stack);
system("pause");
return 0;
}
int initStack(Stack *pStack)
{
//首先创建一个结点,此结点为栈底结点的下一个结点,为了方便操作
Node *node = (Node *)malloc(sizeof(Node));
if (!node)
{
printf("内存分配失败,程序将退出\n");
exit(EXIT_FAILURE);
}
//此结点的下一个结点为NULL
node->next = NULL;
//栈顶和栈底指针都指向此结点
pStack->top = pStack->bottom = node;
return OK;
}
void pushStack(Stack *pStack, ElemType e)
{
Node *newNode = (Node *)malloc(sizeof(Node));
if (!newNode)
{
printf("内存分配失败,程序将退出\n");
exit(EXIT_FAILURE);
}
newNode->data = e;
//新结点的下一个结点为原栈顶结点
newNode->next = pStack->top;
//把栈顶修改为新创建的结点
pStack->top = newNode;
}
int popStack(Stack *pStack, ElemType *e)
{
if (pStack->top == pStack->bottom)
{
printf("出栈失败,栈为空\n");
return ERROR;
}
*e = pStack->top->data;
//先取得栈顶元素
Node *p = pStack->top;
//把栈顶指针指向原栈顶元素的下一个元素
pStack->top = p->next;
//释放原栈顶元素
free(p);
p = NULL;
return OK;
}
void clearStack(Stack *pStack)
{
Node *p = pStack->top;
while (pStack->top != pStack->bottom)
{
p = p->next;
free (pStack->top);
pStack->top = p;
}
}
void traverse(Stack *pStack)
{
Node *p = pStack->top;
while (p != pStack->bottom)
{
printf("%d ", p->data);
p = p->next;
}
printf("\n");
}
栈(链式)
最新推荐文章于 2022-10-08 22:19:49 发布