【发布时间】:2021-05-10 22:45:57
【问题描述】:
数字被压入堆栈,你需要将整个堆栈出栈,然后将小于 10 的元素出栈。移除堆栈的所有元素时的示例代码:
#define _CRT_SECURE_NO_WARNINGS
#include <Windows.h>
#include <stdio.h>
#include <math.h>
#include <malloc.h>
struct kkk
{
float elem[15];
int top; // index of the top rlrment
};
struct kkk* st, * element; // pointers
void Init(struct kkk* st) // initialization
{
st->top = NULL;
}
void Push(struct kkk* st, float f) // push an item onto the stack
{
if (st->top < 15)
{
st->elem[st->top] = f;
st->top++;
}
else
printf("Stack full\n");
}
float Pop(struct kkk* st) // pop an item from the stack
{
float el;
if ((st->top) > 0)
{
st->top--;
el = st->elem[st->top];
return el;
}
else
{
printf("Stack is empty \n");
return 0;
}
}
float Vulychtop(struct kkk* st) // deleting the top of the stack
{
if ((st->top) > 0) {
return(st->elem[st->top - 1]);
}
else {
printf("Stack is empty!\n");
return 0;
}
}
int Gettop(struct kkk* st) // top element of the stack without delting
{
return(st->top);
}
int Isempty(struct kkk* st) // check
{
if ((st->top) == 0)
return 1;
else return 0;
}
void Vuvid(struct kkk* st) // Output of all elements
{
int i;
i = st->top;
if (Isempty(st) == 1) return;
do {
i--;
printf("%f\n", st->elem[i]);
} while (i > 0);
}
int main()
{
SetConsoleCP(1251);
SetConsoleOutputCP(1251);
int i, n, k;
float znach;
element = (struct kkk*)malloc(sizeof(struct kkk));
Init(element);
printf("Enter the number of items in the stack \n");
scanf("%d", &n);
for (i = 0; i < n; i++) {
printf("Enter the number %d: ", i);
scanf("%f", &znach);
Push(element, znach);
}
printf("In stack %d elements \n", Gettop(element));
printf("\n");
Vuvid(element);
printf("Top element %f\n", Vulychtop(element));
do {
printf("The element to be removed %f, ", Pop(element));
printf("Items left in the stack %d \n", Gettop(element));
} while (Isempty(element) == 0);
return 0;
}
结果:https://i.stack.imgur.com/wLczr.png
我创建了一个堆栈,然后我开始向其中输入数字。有了这个,我很好。接下来,我找到堆栈的顶部元素并将其弹出。之后,我需要从堆栈中删除那些值小于10的数字,并且我设法将堆栈一个一个地完全清除。无法为此设定条件。
【问题讨论】:
-
可能用英文文本替换俄文文本。并展示输入和预期与实际输出的示例
-
我不确定你的问题是什么。判断一个数
n是否小于10的条件是n < 10。 -
@Anton Tretiak 您是否需要删除堆栈中小于 10 的所有元素?如果是这样,那么您需要一个辅助堆栈,如果要使用堆栈接口进行操作而不直接访问数组 elem。
-
您是只需要使用栈接口(只需要push和pop)还是可以直接访问底层数组?后一种方式会更简单...
-
@SergeBallesta 不,不需要,我昨天试过这个方法,但不成功。