链栈
#include<malloc.h>
using namespace std;
#define Elemtype int
#define Maxsize 50
//带有头部节点的链栈
typedef struct LinkNode{
Elemtype data;
struct LinkNode *next;
}*LiStack;
//初始化
void InitStack(LiStack &L)
{
L = (LinkNode*)malloc(sizeof(LinkNode));
L->next = nullptr;
}
//栈判空
bool StackEmpty(LiStack L)
{
if(L->next == nullptr)
{
printf("栈为空\n");
return false;
}
else
{
printf("栈不为空\n");
return true;
}
}
//入栈
bool Push(LiStack &L,int e)
{
LinkNode *s = (LinkNode*)malloc(sizeof(LinkNode));
s->data = e;
s->next = L->next;
L->next = s;
return true;
}
//出栈
bool Pop(LiStack &L,int &e)
{
if(L->next == nullptr)
{
printf("栈已空\n");
return false;
}
LinkNode *p = L->next;
e = p->data;
L->next = p->next;
printf("出栈元素值为%d\n",e);
free(p);
return true;
}
//获取顶部元素
bool GetTop(LiStack L,int x)
{
if(L->next == nullptr)
{
printf("栈已空\n");
return false;
}
LinkNode *p = L->next;
x = p->data;
printf("栈顶元素值为%d\n",x);
return true;
}
//打印栈
void PrintStack(LiStack L)
{
LinkNode *n = L->next;
while(n != nullptr)
{
printf("|___%d___|\n",n->data);
n = n ->next;
}
}
int main()
{
LiStack s;
InitStack(s);
StackEmpty(s);
Push(s,1);
Push(s,2);
Push(s,3);
Push(s,4);
StackEmpty(s);
PrintStack(s);
int e,x;
Pop(s,e);
PrintStack(s);
GetTop(s,x);
return 0;
}
保持好奇心!

浙公网安备 33010602011771号