链栈栈的实现方式
代码结构图
LinkElement.h
#ifndef LINKSTACK_H
#define LINKSTACK_H
#include <stdbool.h>
//定义数据类型
typedef int LinkElementType;
/** 定义链栈的结点结构*/
typedef struct StackNode {
LinkElementType data; //结点中保存的元素
struct StackNode *next; //指向下个结点的指针
} StackNode;
/** 链栈结构*/
typedef struct LinkStack {
StackNode * top; //栈顶指针
int length; //链栈的长度(元素个数)
} LinkStack;
//初始化链栈
void InitStack(LinkStack *LS);
//判断链栈是否为空
bool EmptyLinkStack(LinkStack *LS);
//进栈
bool PushLinkStack(LinkStack *LS, LinkElementType element);
//出栈
bool PopLinkStack(LinkStack *LS, LinkElementType *element);
//获取栈顶元素
LinkElementType GetLinkTop(LinkStack *LS);
//清空栈
void ClearLinkStack(LinkStack *LS);
//销毁栈
void DestroyLinkStack(LinkStack *LS);
LinkStack.c
#include "LinkStack.h"
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
//初始化链栈
void InitStack(LinkStack *LS) {
LS->top = NULL;
LS->length = 0;
}
//判断链栈是否为空
bool EmptyLinkStack(LinkStack *LS) {
return LS->length == 0;
}
//进栈
bool PushLinkStack(LinkStack *LS, LinkElementType element) {
StackNode *node = (StackNode *)malloc(sizeof(StackNode));
node->data = element;
node->next = LS->top;
LS->top = node;
LS->length ++;
return true;
}
//出栈
bool PopLinkStack(LinkStack *LS, LinkElementType *element) {
if(EmptyLinkStack(LS)) {
printf("空栈,出栈操作失败!\n");
return false;
}
//获取栈顶元素
*element = LS->top->data;
//记录出栈操作前的栈顶指针
StackNode *node = LS->top;
//栈顶指针下移一位
LS->top = LS->top->next;
//释放原栈顶空间
free(node);
LS->length--;
return true;
}
//获取栈顶元素
LinkElementType GetLinkTop(LinkStack *LS) {
if(EmptyLinkStack(LS)) {
printf("空栈,获取栈顶元素失败!\n");
return -1;
}
return LS->top->data;
}
//清空栈
void ClearLinkStack(LinkStack *LS) {
StackNode * tempNode;
while (LS->top) {
tempNode = LS->top;
//栈顶指向下个元素
LS->top = LS->top->next;
free(tempNode);
LS->length--;
}
}
//销毁栈
void DestroyLinkStack(LinkStack *LS) {
ClearLinkStack(LS);
free(LS);
LS = NULL;
}
main.c
LinkStack S;
InitStack(&S);
LinkElementType a[5]={2,4,6,8,10};
for (int i=0;i<5;i++) {
PushLinkStack(&S,a[i]);
}
printf("栈顶元素:%d\n", GetLinkTop(&S));
LinkElementType e;
PopLinkStack(&S, &e);
printf("出栈元素:%d\n", e);
printf("全部元素出栈:\n");
while(!EmptyLinkStack(&S)){
printf("%d ", GetLinkTop(&S));
PopLinkStack(&S, &e);
}