11 篇文章 3 订阅

# 链式栈的9种基本操作

## 定义常量

/*一些经常用到的头文件，预定义常量等*/
//常用头文件
#include <stdio.h>
#include <malloc.h>
#include <math.h>
#include <stdlib.h>
#include <string.h>
//函数结果状态代码
#define TRUE	1
#define FALSE	0
#define OK		1
#define ERROR	0
#define INFEASIBLE	0
//新建函数类型，表示函数运行结果
typedef int Status;


## 结构体定义和函数声明

typedef int SElemType;
typedef struct SNode
{
SElemType data;
struct SNode* next;
}SNode, * StackPtr;

typedef struct
{
StackPtr base;	//栈底指针
StackPtr top;	//栈底指针

//构造空栈
//销毁栈
//置空栈
//判栈空
//求栈长
//取栈顶元素，用e返回
//压栈
//出栈
//遍历栈

//辅助函数
Status visit(SElemType* e);


## 函数定义

//构造空栈
{
S->top = (StackPtr)malloc(sizeof(SNode));
if (!S->top)		exit(-1);
S->base = S->top;
S->base->next = NULL;
return OK;
}
//销毁栈
{
while (S->top)
{
S->base = S->top->next;
free(S->top);
S->top = S->base;
}
return OK;
}
//置空栈
{
//保存指针
StackPtr p, q;
p = S->top;
//指向空结点
S->top = S->base;
//逐个释放结点
while (p != S->base)
{
q = p->next;
free(p);
p = q;
}
return OK;
}
//判栈空
{
if (S.top == S.base)
return TRUE;
else
return FALSE;
}
//求栈长
{
int len = 0;
StackPtr p = S.top;
while (p != S.base)
{
len++;
p = p->next;
}
return len;
}
//取栈顶元素，用e返回
{
if (S.base == S.top)
return ERROR;
*e = S.top->data;
return OK;
}
//压栈
{
StackPtr temp = (StackPtr)malloc(sizeof(SNode));
if (!temp) exit(-1);
temp->data = e;
//连接
temp->next = S->top;
S->top = temp;
return OK;
}
//出栈
{
if (S->top == S->base)
return ERROR;
StackPtr temp = S->top;
*e = temp->data;
S->top = S->top->next;
free(temp);
return OK;
}
//遍历栈
{
StackPtr p = S.top;
while (p != S.base)
{
visit(&p->data);
p = p->next;
}
printf("\n");
return OK;
}


## 测试

int main()
{
//初始化栈
InitStack(&S);
if (StackEmpty(S))
printf("空栈！\n");
else
printf("不是空栈！\n");
//栈长
printf("栈长为：%d\n", StackLength(S));
//入栈
SElemType i;
for (i = 1; i <= 8; i++)
{
if (Push(&S, i))
printf("入栈成功！\n");
else
printf("入栈失败！\n");
}
//栈长
printf("栈长为：%d\n", StackLength(S));
//栈顶元素
SElemType e;
if (GetTop(S, &e))
printf("栈顶元素：%d\n", e);
else
printf("获取失败！\n");
//遍历栈
StackTraverse(S, visit);
//出栈
if (Pop(&S, &e))
printf("出栈成功：%d\n", e);
else
printf("出栈失败！\n");
if (Pop(&S, &e))
printf("出栈成功：%d\n", e);
else
printf("出栈失败！\n");
//栈长
printf("栈长为：%d\n", StackLength(S));
//栈顶元素
if (GetTop(S, &e))
printf("栈顶元素：%d\n", e);
else
printf("获取失败！\n");
//遍历栈
StackTraverse(S, visit);
//清空
if (ClearStack(&S))
printf("清空成功！\n");
else
printf("清空失败！\n");
//栈长
printf("栈长为：%d\n", StackLength(S));
//栈顶元素
if (GetTop(S, &e))
printf("栈顶元素：%d\n", e);
else
printf("获取失败！\n");
//销毁栈
if (DestroyStack(&S))
printf("销毁成功！\n");
else
printf("销毁失败！\n");
return 0;
}

//辅助函数
Status visit(SElemType* e)
{
printf("%d ", *e);
return OK;
}


## 运行结果

• 3
点赞
• 0
评论
• 13
收藏
• 打赏
• 扫一扫，分享海报

10-27
01-15 3548

01-22 2446
01-21 922
04-18 5759
04-29 556
04-13 403
12-26 1万+
11-29 815
07-25 1万+
05-23 1110
02-03 545
06-30 6569
04-01 80
11-27 1231

CoderGou

¥2 ¥4 ¥6 ¥10 ¥20

1.余额是钱包充值的虚拟货币，按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载，可以购买VIP、C币套餐、付费专栏及课程。