单链栈在结构上与单链表相似,节点存储一个data值,并通过next指针链接。但由于存储结构为栈,与单链表不同,单链栈的头节点位于栈顶。
栈顶--------------------------------------栈底
单链栈的结构定义:一个data值以及一个指向下一节点的指针。
#include<stdio.h>
#include<malloc.h>
typedef struct SqNode {
int data;
struct SqNode* next;
}LinkSqNode;
单链栈的初始化:malloc函数开辟一个头节点S的空间,并将其next指向NULL。
void InitLinkSq(LinkSqNode*& S)
{
S = (LinkSqNode*)malloc(sizeof(LinkSqNode));
S->next = NULL;
}
单链栈的销毁:与单链表相反,由头节点开始从栈顶元素删到栈底元素。
void DestroyLinkSq(LinkSqNode*& S)
{
LinkSqNode* pre = S, * p = pre->next;
while (p != NULL)
{
free(pre);
pre = p;
p = p->next;
}
free(p);
}
检查是否为空:头节点后是否有元素。
bool EmptyLinkSq(LinkSqNode* S)
{
return S->next == NULL;
}
进栈操作:
void PushS(LinkSqNode*& S, int a)
{
LinkSqNode* p = (LinkSqNode*)malloc(sizeof(LinkSqNode));
p->data = a;
p->next = S->next;
S->next = p;
}
出栈操作(先检查单链栈是否为空):
bool PullS(LinkSqNode*& S,int&a)
{
if (S->next != NULL)
{
LinkSqNode* p = S->next;
a = p->data;
S->next = p->next;
free(p);
return true;
}
return false;
}
取栈顶元素(为空则返回假):
bool GetTopS(LinkSqNode* S, int& a)
{
if (S->next != NULL)
{
a = S->next->data;
return true;
}
else
return false;
}
从栈顶到栈底依次输出元素:
void DispLinkSq(LinkSqNode* S)
{
if (S->next != NULL)
{
LinkSqNode* p = S;
while (p->next != NULL)
{
p = p->next;
printf("%d ", p->data);
}
printf("\n");
}
else
printf("该单链栈为空。\n");
}
最后在main()函数上实现:
int main()
{
LinkSqNode* S;
InitLinkSq(S);
if (EmptyLinkSq)
printf("单链栈为空。\n");
else {
printf("单链栈不为空。\n");
}
printf("\n开始进栈。\n");
for (int i = 0; i < 8; i++)
{
printf("在栈顶增加元素%d:", i);
PushS(S, i);
DispLinkSq(S);
}
printf("\n开始出栈。\n");
for (int i = 0; i < 4; i++)
{
int value = 0;
PullS(S, value);
printf("去除栈顶元素%d:", value);
DispLinkSq(S);
}
int a = 0;
if (GetTopS(S, a))
printf("此时栈顶元素为:%d", a);
DestroyLinkSq(S);
}