0.链栈的数据结构定义
typedef struct LinkNode {
ElemType data;
struct LinkNode* next;
}LinkNode, * LinkStack;
1.链栈的初始化
void InitStack(LinkStack& S)
{
S = NULL;
}
2.进栈
Status Push(LinkStack& S, ElemType e)
{
LinkNode* x = (LinkNode*)malloc(sizeof(LinkNode));
if (x == NULL)
return false;
x->data = e;
x->next = S;
S = x;
return true;
}
3.出栈
Status Pop(LinkStack& S, ElemType& e)
{
if (S == NULL)
return false;
e = S->data;
LinkNode* q;
q = S;
S = S->next;
free(q);
return true;
}
4.读取栈顶元素
Status GetTop(LinkStack S, ElemType& e)
{
if (S == NULL)
return false;
e = S->data;
return true;
}
5.判空
Status StackEmpty(LinkStack S)
{
if (S == NULL)
return true;
else
return false;
}
全部代码
#include<stdio.h>
#include<stdlib.h>
typedef int ElemType;
typedef bool Status;
typedef struct LinkNode {
ElemType data;
struct LinkNode* next;
}LinkNode, * LinkStack;
void InitStack(LinkStack& S)
{
S = NULL;
}
Status Push(LinkStack& S, ElemType e)
{
LinkNode* x = (LinkNode*)malloc(sizeof(LinkNode));
if (x == NULL)
return false;
x->data = e;
x->next = S;
S = x;
return true;
}
Status Pop(LinkStack& S, ElemType& e)
{
if (S == NULL)
return false;
e = S->data;
LinkNode* q;
q = S;
S = S->next;
free(q);
return true;
}
Status GetTop(LinkStack S, ElemType& e)
{
if (S == NULL)
return false;
e = S->data;
return true;
}
Status StackEmpty(LinkStack S)
{
if (S == NULL)
return true;
else
return false;
}
int main()
{
ElemType x = -1;
LinkStack S;
InitStack(S);
Push(S, 6);
GetTop(S, x);
printf("%d", x);
if (StackEmpty)
{
printf("栈为空\n");
}
else
{
printf("栈为非空\n");
}
return 0;
}