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

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

以下代码是基于C语言写的堆栈的压栈,出栈,清栈,读栈指针等方法,在Visual studio 中,可直接使用,供学习者参考学习。


#include
#include
#include
#include
#include
#include
#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 d出 data:%c,top value is %d\n”, chd, s1.top);
chd = pop(&s1);
printf(“Stack d出 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;
}

欢迎分享,转载请注明来源:内存溢出

原文地址:https://www.54852.com/langs/674696.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-04-19
下一篇2022-04-19

发表评论

登录后才能评论

评论列表(0条)

    保存