#include <stdio.h>
#include <stdlib.h>
typedef int ElemType;
typedef struct Node{
ElemType data;
struct Node *next;
}StackNode, Stack;
void Init(Stack *s);
bool IsEmpty(Stack *s);
void Push(Stack *s, ElemType e);
void Pop(Stack *s, ElemType *e);
void GetTop(Stack *s, ElemType *e);
void Print(Stack *s);
void Clear(Stack *s);
void Init(Stack *s)
{
s->next = NULL;
}
bool IsEmpty(Stack *s)
{
return (s->next == NULL) ? true : false;
}
void Push(Stack *s, ElemType e)
{
StackNode *node = (StackNode *)malloc(sizeof(StackNode));
node->data = e;
node->next = s->next;
s->next = node;
}
void Pop(Stack *s, ElemType *e)
{
if (!IsEmpty(s))
{
StackNode *temp = s->next;
*e = temp->data;
s->next = temp->next;
}
}
void GetTop(Stack *s, ElemType *e)
{
if (!IsEmpty(s))
*e = s->next->data;
}
void Print(Stack *s)
{
StackNode *p = s->next;
while (p)
{
printf("%d ", p->data);
p = p->next;
}
printf("\n");
}
void Clear(Stack *s)
{
StackNode *p = s->next;
while (p)
{
StackNode *temp = p;
p = p->next;
free(temp);
}
s->next = NULL;
}
int main()
{
ElemType e;
Stack s;
Init(&s);
for(int i = 1; i <= 20; ++i)
Push(&s, i);
Print(&s);
GetTop(&s, &e);
printf("栈顶的元素为:%d\n", e);
Pop(&s, &e);
GetTop(&s, &e);
printf("出栈一次,栈顶的元素为:%d\n", e);
Clear(&s);
printf("清空该栈,此时");
if(IsEmpty(&s))
printf("栈为空\n");
else
printf("栈不为空\n");
return 0;
}
链式栈的实现
最新推荐文章于 2024-01-10 21:44:16 发布