0

有一项任务要求我制作特定结构的物品并堆叠无限数量的物品。我还应该能够弹出列表顶部的项目。我已经能够将它们堆叠起来,但是当我尝试弹出我的程序时会冻结。

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);



}
4

1 回答 1

0

查看您的pop函数(格式正确):

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;
}

如果您的堆栈不为空,则current != nullptr. 你永远不会改变它的价值,也永远不会退出循环。这是适用于非空堆栈的代码:

    while (true) // current is always != nullptr
        if (true) { // (current == stack->top) is always true
            current->value = value;
            stack->top = current->next;
            // current is never changed
        }

你可能的意思是:

double pop(Stack* stack){
    Item *current = stack->top;
    if (current) {
        double value = current->value;
        stack->top = current->next;
        stack->size--;
        delete current;
        return value; 
    }
    return HUGE_VAL;
}
于 2020-06-24T05:30:25.197 回答