基于C语言堆栈push,pop,gettop,destorystack,isEmpty,isFull实现

以下代码是基于C语言写的堆栈的压栈,出栈,清栈,读栈指针等方法,在Visual studio 中,可直接使用,供学习者参考学习。
#include<cStack.h>
#include <malloc.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdbool.h>
#include

#define MAX_SIZE 100
typedef struct Stack
{
char *data;
int size;
int top;
};
#endif
//init stack
void initStack(Stack s)
{
s->data = (char
)malloc(MAX_SIZE * sizeof(char)); //分配最大内存空间
if (!s->data)
exit(OVERFLOW); //提前终止程序
s->size = MAX_SIZE;
s->top = -1;
}
void destroyStack(Stack *s)
{
free(s->data);
}
bool push(Stack *s, char ch)
{
if ((s->top + 1) != s->size)
{
s->data[++s->top] = ch;
return true;
}
else
return false;
}
char pop(Stack *s)
{
if (s->top != -1)
return s->data[s->top–];
}
char gettop(Stack *s)
{
return s->data[s->top];
}
bool isEmpty(Stack *s)
{
if (s->top == -1)
return true;
else
return false;
}
bool isFull(Stack *s)
{
if ((s->top + 1) == s->size)
return true;
else
return false;
}
void setNull(Stack *s)
{
s->top = -1;
}

int main()
{
char chd;
bool c;
Stack s1;
initStack(&s1);
c = push(&s1, ‘a’);
printf(“Stack s1 push status is %d,s.data is %c,top value is %d\n”, c,s1.data[s1.top],s1.top);
c = push(&s1, ‘b’);
printf(“Stack s1 push status is %d,s.data is %c,top value is %d\n”, c, s1.data[s1.top], s1.top);
chd = gettop(&s1);
printf(“Stack s1->top data:%c,top value is %d\n”, chd, s1.top);
chd = pop(&s1);
printf(“Stack 弹出 data:%c,top value is %d\n”, chd, s1.top);
chd = pop(&s1);
printf(“Stack 弹出 data:%c,top value is %d\n”, chd, s1.top);
c = isEmpty(&s1);
printf(“Stack s1 c bool:%d,top value is %d\n”, c, s1.top);
c = isFull(&s1);
printf(“Stack s1 c bool:%d,top value is %d\n”, c, s1.top);
return 0;
}

  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Linus_Yan

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值