/*冒昧问一句,你们是不是一直段错误????*/
/*我也是看了别人的才发现这个问题:(41条消息) 6-1 反向输出整数序列 10分【数据结构·顺序栈模拟】_超级码力666的博客-优快云博客
*/
题目描述
输入一个整数序列(非负整数,只含 正整数 和 0 )。序列以 -1 结束。要求反向输出这个非负整数序列。
要求定义一个栈来实现这个程序的功能。
输入
一个整数序列,每个数之间以空格隔开,非负整数,只含 正整数 和 0 。输入-1 表示输入结束。
输出
反向输出这个非负整数序列。
提示:
1、在C语言程序中使用 bool 类型,必须包含头文件 stdbool.h
2、题目要求创建栈时,栈空间有16个存储单元。但是服务器测试数据有超过50万个数据需要输入。因此,要求Push操作检查当前存储空间是否已满。若当前存储空间已满,则需要把容量(capacity)扩大为原来容量的2倍。/*注意这里说了要50万空间,我之前一直就是卡在这里,一直说我段错误!!!*/
3、在Pop操作中,也要求检查容量。若弹出1个元素后,已用空间只有容量的三分之一,把容量减少为原来容量的一半。
ok,废话不多说上代码
#define _CRT_SECURE_NO_WARNINGS
#define shuiyunsheng 6666666666
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
typedef int ElemType;
struct StackRecord;
typedef struct StackRecord* Stack;
struct StackRecord
{
ElemType* base; //指向栈的元素存储空间
int top; // 栈顶
int capacity; // 当前已分配空间,以元素为单位
};
Stack createStack(void) //初始化一个空栈。空栈拥有16个元素的空间,栈顶值为 -1{
{
Stack k = (Stack)malloc(sizeof(struct StackRecord));
k->capacity = 500000;/*特别注意这个数据*/
k->top = 0;
k->base = (int*)malloc(sizeof(int) * k->capacity);
return k;
}
void push(Stack pStack, ElemType x)//把 x 入栈
{
Stack k = pStack;
if (k->top == k->capacity)
return ;
k->base[k->top++] = x;
if (k->top == k->capacity)
k->capacity *= 2;
return;
}
ElemType top(Stack pStack)//返回当前栈顶元素的值
{
if (pStack->top == 0)
return;
return pStack->base[pStack->top-1];
}
void pop(Stack pStack) //当前栈顶元素出栈
{
Stack k = pStack;
if (k->top == 0)
return;
k->base[k->top--];
if (k->top <= k->capacity / 3)
{
k->capacity /= 2;
}
return;
}
bool empty(Stack pStack)//如果栈空,则返回 true,否则返回 false
{
Stack k = pStack;
if (k->top == 0)
return true;
return false;
}
void destroy(Stack pStack)//清空分配给栈的存储空间
{
free(pStack->base);
}
int main(void)
{
Stack pStack;
pStack = createStack();
int x;
scanf("%d", &x);
while (x != -1)
{
push(pStack, x);
scanf("%d", &x);
}
while (!empty(pStack))
{
x = top(pStack);
printf("%d ", x);
pop(pStack);
}
destroy(pStack);
return 0;
}
/* 请在这里填写答案 */
本文介绍了如何使用C语言通过顺序栈实现一个程序,该程序接收一个非负整数序列,并在输入-1时反向输出序列。文章详细解释了栈的创建、压入、弹出、检查栈顶元素和判断栈空的操作,并提供了完整的代码实现,特别关注了栈容量的动态调整以适应大规模数据输入的需求。
575

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



