【王道数据结构】栈的链式存储——链栈(带头结点)
作者:
Skuy
,
2023-03-22 20:47:51
,
所有人可见
,
阅读 274
#include <stdio.h>
#include <stdlib.h>
typedef struct Linknode{
int data;
struct Linknode *next;
} LNode, *LinkStack;
// 链栈的初始化(带头结点)
bool InitLinkStack(LinkStack &S)
{
S = (LNode *) malloc(sizeof(LNode));
if (S == NULL) return false;
S->next = NULL;
return true;
}
// 判空
bool StackEmpty(LinkStack S)
{
if (S->next == NULL) return true;
else return false;
}
// 入栈
bool Push(LinkStack &S, int e)
{
LNode *p = (LNode *) malloc(sizeof(LNode));
if (p == NULL) return false;
p->data = e;
p->next = S->next;
S->next = p;
return true;
}
// 出栈
bool Pop(LinkStack &S, int &x)
{
if (StackEmpty(S)) return false; // 此时是空栈
LNode *p = S->next;
x = p->data;
S->next = p->next;
free(p);
return true;
}
// 读取栈顶元素
bool GetTop(LinkStack S, int &x)
{
if (StackEmpty(S)) return false;
x = S->next->data;
return true;
}
void test()
{
LinkStack S;
InitLinkStack(S);
// Push(S, 1);
// Push(S, 2);
// Push(S, 3);
// int i = 0;
// Pop(S, i);
// int x = 0;
// if (GetTop(S, x)) printf("%d\n", x);
// else printf("The Stack is empty!\n");
}
int main()
{
test();
return 0;
}