栈的链表实现(C语言)
1、头文件
(Stack.h)
#pragma once
/*
* 栈ADT的链表实现
*/
#include <stdio.h>
#include <stdlib.h> //malloc
#include <stdbool.h> //bool类型
struct Stack* CreateStack();
bool IsEmpty(struct Stack* s);
void DisposeStack(struct Stack* s);
void MakeEmpty(struct Stack* s);
void Push(int x, struct Stack* s);
int Top(struct Stack* s);
void Pop(struct Stack* s);
struct Stack
{
int element;
struct Stack* next;
};
2、主函数
(main.c)
#include "Stack.h"
int main()
{
int val;
struct Stack* s;
//创建一个栈
s = CreateStack();
//压栈
Push(5, s);
Push(2, s);
//显示栈中的元素值
DisposeStack(s);
printf("-----------------\n");
//查看栈顶元素值
val = Top(s);
printf("top val is:%d\n", val);
printf("-----------------\n");
//栈顶元素出栈
Pop(s);
val = Top(s);
printf("top val is:%d\n", val);
printf("-----------------\n");
Push(6, s);
Push(7, s);
DisposeStack(s);
printf("-----------------\n");
//清空栈
MakeEmpty(s);
//DisposeStack(s);
printf("stack IsEmpty:%d\n", IsEmpty(s));
return 0;
}
3、函数的实现
3.1 CreateStack.c
#include "Stack.h"
struct Stack* CreateStack()
{
struct Stack* p = malloc(sizeof(struct Stack));
if (NULL == p) {
printf("内存空间不足,创建空栈失败");
exit(1);
}
p->next = NULL;
return p;
}
3.2 IsEmpty.c
#include "Stack.h"
bool IsEmpty(struct Stack* s)
{
return NULL == s->next;
}
3.3 DisposeStack.c
#include "Stack.h"
void DisposeStack(struct Stack* s)
{
struct Stack* p = s->next;
if (NULL == s->next) {
printf("本栈为空");
return;
}
while (NULL != p) {
printf("%d ", p->element);
p = p->next;
}
printf("\n");
}
3.4 MakeEmpty.c
#include "Stack.h"
void MakeEmpty(struct Stack* s)
{
if (NULL == s) {
printf("Must use CreateStack first.\n");
return;
}
else {
while (!IsEmpty(s)) {
Pop(s);
}
}
}
3.5 Push.c
#include "Stack.h"
void Push(int x, struct Stack* s)
{
struct Stack* p = malloc(sizeof(struct Stack));
if (NULL == p) {
printf("内存空间不足,push失败");
exit(1);
}
p->element = x;
p->next = s->next;
s->next = p;
}
3.6 Top.c
#include "Stack.h"
int Top(struct Stack* s)
{
if (NULL == s->next) {
printf("此栈为空栈,违法读取栈顶");
return 0;
}
return s->next->element;
}
3.7 Pop.c
#include "Stack.h"
void Pop(struct Stack* s)
{
s->next = s->next->next;
}
4、写在后面
为方便大家学习,我已经将原码上传到了GitHub,欢迎大家下载讨论。链接:link(文件名为:栈的链表实现)。