数据结构3.0顺序栈的push,pop

这篇博客介绍了如何使用C语言实现顺序栈的数据结构,包括初始化栈、判断栈满、压栈(push)、弹栈(pop)以及检查栈空的操作。示例代码展示了如何创建一个顺序栈,并进行元素的压入和弹出,最后清理栈内存。

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>

typedef struct SNODE
{
int *data;
int top;
int MAXSIZE;
}*stack, node;

stack initi_stack(int n);
bool is_full(stack plist);
bool push(stack plist, int val);
bool pop(stack plist, int *val);
bool is_empty(stack plist);

int main(void)
{
int lens;
int val;
int i;
printf(“请输入您要生成的栈的大小:\n”);
scanf("%d", &lens);
stack S = initi_stack(lens);
push(S, -1314);
push(S, -25);
push(S, 52);
push(S, 727);
for ( i = 0; i <= S->top; i++)
{
printf("%d “, S->data[i]);
}
printf(”\n");
pop(S, &val);
for ( i = 0; i <= S->top; i++)
{
printf("%d “, S->data[i]);
}
printf(”\n");
free(S->data);
free(S);
S = NULL;
return 0;
}

stack initi_stack(int n)
{
stack tmp = (stack) malloc(sizeof(node));
if(NULLtmp)
{
exit(-1);
}
tmp->MAXSIZE = n;
tmp->top = -1;
tmp->data = (int *)malloc(sizeof(int) * n);
if(NULL
tmp->data)
{
exit(-1);
}
return tmp;
}

bool is_full(stack plist)
{
if(plist->top == plist->MAXSIZE-1)
{
return true;
}
else
{
return false;
}

}

bool push(stack plist, int val)
{
if(is_full(plist))
{
printf(“stack is full, failed!\n”);
return false;
}

plist->data[++(plist->top)] = val;
return true;

}

bool is_empty(stack plist)
{
if(plist->top==-1)
{
return true;
}
else
{
return false;
}

}
bool pop(stack plist, int *val)
{
if(is_empty(plist))
{
printf(“no factor in stack,failed!\n”);
return false;
}
*val = plist->data[plist->top];
plist->top–;
return true;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值