/*************************************************
*
* file name:LkStack.c
* author :[email protected]
* date :2024/04/25
* brief :构建链栈
* note :None
*
* CopyRight (c) 2024 [email protected] All Right Reseverd
*
**************************************************/
#include <stdbool.h>
#include <stdlib.h>
#include <stdio.h>
/*************************************************
*
* func name :
* brief :
* func parameter:
*
*
* return :None
* note :None
* func author :[email protected]
* date :2024/04/25
* version :V1.0
**************************************************/
typedef int DataType_t;
typedef struct LkStack // 存储栈的数据(栈底+栈顶)
{
DataType_t Data; // 结点的数据域
struct LkStack *Top; // 栈顶
} LkStack_t;
// 创建一个空的链栈
LkStack_t *LkStack_Create(void)
{
LkStack_t *Bottom = (LkStack_t *)calloc(1, sizeof(LkStack_t));
if (NULL == Bottom)
{
perror("calloc memory for Bottom is failed!\n");
exit(-1);
}
Bottom->Top = NULL;
return Bottom;
}
// 创建一个新结点,并对新结点进行初始化
LkStack_t *LkStack_NewNode(DataType_t data)
{
LkStack_t *NewNode = (LkStack_t *)calloc(1, sizeof(LkStack_t));
NewNode->Data = data;
NewNode->Top = NULL;
}
// 新元素从栈顶入栈,即从链表的头部插入元素
bool LkStack_Push(LkStack_t *Bottom, DataType_t data)
{
LkStack_t *NewNode = LkStack_NewNode(data);
if (NULL == Bottom->Top) // 判断链表是否为空
{
// 链表为空
Bottom->Top = NewNode;
return true;
}
// 2.2链表非空
{
NewNode->Top = Bottom->Top;
Bottom->Top = NewNode;
return true;
}
}
// 判断栈是否为空
bool LkStack_IsEmpty(LkStack_t *Bottom)
{
if (Bottom->Top == NULL)
return true;
return false;
}
DataType_t LkStack_Pop(LkStack_t *Bottom)
{
DataType_t temp = 0; // 存储出栈元素的值
// 判断栈是否为空
if (LkStack_IsEmpty(Bottom))
{
printf("LkStack is empty!\n");
return;
}
temp = Bottom->Top->Data;
LkStack_t *Pbottom = Bottom->Top; // 备份首节点地址,用于最后释放首结点地址
Bottom->Top = Pbottom->Top;
Pbottom->Top = NULL;
free(Pbottom);
printf("the poped element is %d\n", temp);
return temp;
}
// 遍历顺序栈元素(测试函数)
bool LkStack_Print(LkStack_t *Bottom)
{
LkStack_t *Pbottom = Bottom; // 备份头结点
if (NULL == Bottom->Top) // 判断链表是否为空,为空直接退出
{
printf("LkStacK is empty\n");
return false;
}
while (Pbottom->Top)
{
Pbottom = Pbottom->Top; // 遍历链表
printf(" %d", Pbottom->Data); // 打印链表
}
printf("\n");
return true;
}
int main(void)
{
LkStack_t *Bottom = LkStack_Create();
LkStack_Push(Bottom, 1);
LkStack_Push(Bottom, 2);
LkStack_Push(Bottom, 3);
LkStack_Push(Bottom, 4);
LkStack_Print(Bottom);
LkStack_Pop(Bottom);
LkStack_Pop(Bottom);
LkStack_Print(Bottom);
return 0;
}
标签:return,Bottom,LkStack,程序,接口,链栈,Pbottom,NewNode,Top
From: https://www.cnblogs.com/bell-c/p/18158882