#include "pch.h"
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <string.h>
// 因为栈链结点是动态分配的,不考虑栈溢出
typedef struct LNode
{
int data;
struct LNode *next;
}LNode;
// 栈初始化【带头结点】
void intiStack(LNode *&lst)
{
lst = (LNode *)malloc(sizeof(LNode));
memset(lst, 0, sizeof(LNode));
lst->next = NULL;
}
// 判断栈是否为空
int isEmpty(LNode *lst)
{
return lst->next == NULL;
}
// 头结点指向栈顶 用头插法
void push(LNode *lst, int x)
{
LNode *p;
p = (LNode *)malloc(sizeof(LNode));
memset(p, 0, sizeof(LNode));
p->data = x;
p->next = lst->next;
lst->next = p;
}
// 弹栈
int Pop(LNode *lst, int *x)
{
if (isEmpty(lst))
{
puts("栈空");
return 0;
}
// 相当于单链表删除
LNode *p = lst->next; // 指向栈顶
*x = p->data; // 获取数据
lst->next = p->next;
free(p);
return 1;
}
int main()
{
LNode * A;
intiStack(A);
// 压栈
printf(" 将1,2,3,4 放入栈中 ");
for ( int i = 1; i < 5; i++)
{
push(A, i);
}
// 持续弹栈
printf(" \n 不断弹出栈中元素 直到栈空 ");
while (A->next!= NULL)
{
int x;
Pop(A, &x);
printf(" %d ", x);
}
}
效果图如上图