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