有一项任务要求我制作特定结构的物品并堆叠无限数量的物品。我还应该能够弹出列表顶部的项目。我已经能够将它们堆叠起来,但是当我尝试弹出我的程序时会冻结。
pop 函数的规则如下:“在栈顶查找项,将其值保存到变量中,使其下一项成为新的栈顶。使用删除运算符将其内存返回给操作系统, 将堆栈大小减 1,并返回其保存的值。如果堆栈为空,则返回头文件中定义的常量变量 HUGE_VAL。在删除之前获取弹出项的值至关重要;不要'不访问已删除项目的值。"
我也遇到了 HUGE_VAL 的问题,它告诉我它是未定义的,即使它是来自其中一个导入的常量。下面是我的代码:
请告诉我我可能做错了什么
#include <iostream>
#include <iomanip>
#include <string>
#include <cmath>
#include <math.h>
using namespace std;
struct Item{
double value; // The actual value of the item
Item* next; // A pointer to the item beneath
};
struct Stack {
Item* top; // A pointer to the item at the top
int size; // How many items are in the stack? 0 if the stack is empty
};
void push(Stack* stack, double num) {
Item* item = new Item;
item->value = num;
item->next = nullptr;
if(stack->top){
item->next= stack->top;
}
stack->top = item;
stack->size++;
}
double pop(Stack* stack){
Item *current = stack->top; //identifying the value at the top of the stack
double value; //variable to store the value of the Item to be popped
while(current)
if(current == stack->top){
current->value = value;
stack->top = current->next;
}else{
return HUGE_VAL;
}
stack->size--;
delete current;
return 0;
}
void printStack(const Stack* stack){
Item* item = stack->top;
while(item){
cout<< item->value <<endl;
item = item->next;
}
}
int main(){
Stack stack ={nullptr, 0};
push(&stack, 12 );
push(&stack, 23 );
push(&stack, 11.0 );
printStack(&stack);
pop(&stack);
printStack(&stack);
}