#include"stdio.h"
#include"stdlib.h"
typedef int ElemType;
typedef struct LinkNode {
ElemType data;
struct LinkNode* next;
}LinkNode,*LiStack;
typedef struct {
LiStack top;
int count;
}LinkStack;
void visit(ElemType e) {
printf("%d\n", e);
}
void InitLinkStack(LinkStack &S) {
S.top = (LiStack)malloc(sizeof(LinkNode));
if (!S.top)
printf("建表错误!");
S.top = NULL;
S.count = 0;
}
void ClearLiStack(LinkStack& S) {
LiStack p,q;
p = S.top;
while (p) {
q = p;
p = p->next;
free(q);
}
S.count = 0;
}
bool StackEmpty(LinkStack S) {
if (S.count == 0)
return true;
else
return false;
}
int StackLength(LinkStack S) {
return S.count;
}
bool GetTop(LinkStack S,ElemType &e) {
if (S.top == NULL)
return false;
else
e = S.top->data;
return true;
}
bool Push(LinkStack& S, ElemType e) {
LiStack s = (LiStack)malloc(sizeof(LinkNode));
s->data = e;
s->next = S.top;
S.top = s;
S.count++;
return true;
}
bool Pop(LinkStack& S, ElemType& e) {
if (S.count == 0)
return false;
LiStack s;
s = S.top;
e = S.top->data;
S.top = S.top->next;
free(s);
S.count--;
return false;
}
bool StackTraverse(LinkStack S) {
LiStack p;
p = S.top;
while (p) {
visit(p->data);
p = p->next;
}
printf("\n");
return true;
}
int main() {
int i;
LinkStack s;
int e;
InitLinkStack(s);
for (i = 9; i >= 1; i--)
Push(s, i);
printf("栈中元素:\n");
StackTraverse(s);
Pop(s, e);
printf("%d\n", e);
printf("1代表清空%d\n",StackEmpty(s));
GetTop(s,e);
printf("%d\n", e);
ClearLiStack(s);
printf("1代表清空%d\n", StackEmpty(s));
}
链栈的实现与测试
最新推荐文章于 2022-06-17 11:39:59 发布