#include<stdio.h>
#include<malloc.h>
//带头结点
typedef struct Linknode {
int data;
struct Linknode* next;
}LiStack;
void InitStack(LiStack *&s) {
s = (LiStack*)malloc(sizeof(LiStack));
s->next = NULL;
}
//销毁链栈
void destroyStack(LiStack *s) {
LiStack* p = s->next;
while (p != NULL) {
free(s);
s = p;
p = p->next;
}
}
//判断是否为空
bool StackEmpty(LiStack* s) {
if (s->next == NULL)
return true;
else
return false;
}
//进栈
void push(LiStack* s, int e) {
LiStack* p;
p = (LiStack*)malloc(sizeof(LiStack));
p->data = e;
p->next = s->next;
s->next = p;
}
//出栈
bool Pop(LiStack* s, int& e) {
LiStack* p;
if (s->next == NULL)
return false;
p = s->next;
e = p->data;
s->next = p->next;
free(p);
return true;
}
//取栈顶
bool Gettop(LiStack* s, int e) {
if (s->next == NULL)
return false;
e = s->next->data;
return true;
}
//主函数
int main() {
int e;
LiStack*h;
printf("链栈的算法如下:");
printf("初始化栈--->");
InitStack(h);
printf("栈为%s\n", (StackEmpty(h) ? "空" : "非空"));
printf("依次输入元素:--->");
push(h, 1);
push(h, 2);
push(h, 3);
push(h, 4);
push(h, 5);
printf("栈为%s \n", (StackEmpty(h) ? "空" : "非空"));
printf("出栈--->");
while (!StackEmpty(h)) {
Pop(h, e);
printf("%d ", e);
}
printf("\n");
printf("栈为%s\n", (StackEmpty(h) ? "空" : "非空"));
printf("释放栈--->\n");
destroyStack(h);
return 0;
}