带头结点链栈
有问题评论区一起讨论
#include<stdio.h>
#include<malloc.h>
typedef int ElemType;
typedef struct LinkNode {
ElemType data;
struct LinkNode* next;
}LinkNode, * LiStack;
//初始化链栈
void InitStack(LiStack&);
//判断栈空
bool StackEmpty(LiStack);
//压栈
bool Push(LiStack, ElemType);
//出栈
bool Pop(LiStack, ElemType&);
//获取栈顶元素
bool GetTop(LiStack, ElemType&);
//销毁栈
void DestroyStack(LiStack&);
//遍历栈
void Traverse(LiStack);
int main(void) {
LiStack S;
InitStack(S);
bool flag = StackEmpty(S);
if (flag) {
printf("栈空!\n");
}
for (int i = 1; i <= 17; i++) {
flag = Push(S, i);
}
Traverse(S);
ElemType x;
flag = GetTop(S, x);
printf("栈顶元素:%d\n", x);
for (int i = 1; i <= 16; i++) {
if (!Pop(S, x)) {
break;
}
printf("%d\t", x);
}
DestroyStack(S);
Traverse(S);
return 0;
}
void InitStack(LiStack& S) {
S = (LinkNode*)malloc(sizeof(LinkNode));
if (S == NULL) {
printf("内存分配失败!\n");
return;
}
S->next = NULL;
}
bool StackEmpty(LiStack S) {
return S == NULL || S->next == NULL;
}
bool Push(LiStack S, ElemType x) {
LinkNode* node = (LinkNode*)malloc(sizeof(LinkNode));
if (node == NULL) {
printf("内存分配失败!\n");
return false;
}
node->data = x;
node->next = S->next;
S->next = node;
return true;
}
bool Pop(LiStack S, ElemType& x) {
if (StackEmpty(S)) {
printf("栈空!\n");
return false;
}
LinkNode* p = S->next;
x = p->data;
S->next = p->next;
free(p);
return true;
}
bool GetTop(LiStack S, ElemType& x) {
if (StackEmpty(S)) {
printf("栈空!\n");
return false;
}
x = S->next->data;
return true;
}
void DestroyStack(LiStack& S) {
if (StackEmpty(S)) {
S = NULL;
return;
}
ElemType x;
while (Pop(S, x));
free(S);
S = NULL;
}
void Traverse(LiStack S) {
if (StackEmpty(S)) {
printf("栈空!\n");
return;
}
LinkNode* p = S->next;
while (p != NULL) {
printf("%d\t", p->data);
p = p->next;
}
printf("\n");
}