#include <stdio.h>
#include <stdlib.h>
#define INFINITY 65535
#define MAXSIZE 100
typedef int ElemType;
typedef struct {
ElemType data[MAXSIZE];
int top;
}Stack;
void Init(Stack *s);
bool IsEmpty(Stack *s);
ElemType Top(Stack *s);
ElemType Pop(Stack *s);
void Push(Stack *s);
void Print(Stack *s);
void Clear(Stack *s);
void Init(Stack *s)
{
s->top = -1;
}
bool IsEmpty(Stack *s)
{
return (s->top == -1) ? true : false;
}
ElemType Top(Stack *s)
{
if (!IsEmpty(s))
return s->data[s->top];
return INFINITY;
}
ElemType Pop(Stack *s)
{
if (!IsEmpty(s))
return s->data[s->top--];
return INFINITY;
}
void Push(Stack *s, ElemType e)
{
if (s->top >= MAXSIZE - 1)
return;
s->data[++s->top] = e;
}
void Print(Stack *s)
{
for (int i = 0 ; i <= s->top; ++i)
printf("%d ", s->data[i]);
printf("\n");
}
void Clear(Stack *s)
{
s->top = -1;
}
int main()
{
Stack s;
Init(&s);
for(int i = 1; i <= 20; ++i)
Push(&s, i);
Print(&s);
printf("栈顶的元素为:%d\n", Top(&s));
Clear(&s);
printf("清空该栈,此时");
if(IsEmpty(&s))
printf("栈为空\n");
else
printf("栈不为空\n");
return 0;
}顺序栈的实现
最新推荐文章于 2024-08-01 09:21:53 发布
本文详细介绍了C语言中栈的基本概念、实现方法及应用实例,包括初始化、判断是否为空、获取栈顶元素、弹出元素和清空栈等核心操作。通过实践示例,展示了如何使用栈解决实际问题。
1351

被折叠的 条评论
为什么被折叠?



