如何使用结构和指针推动和弹出一堆双打



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

弹出函数的规则如下: "在堆栈顶部查找项目,将其值保存到变量中,使其下一个项目成为新的堆栈顶部。使用 delete 运算符将其内存返回到操作系统,将堆栈大小递减 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);

}

查看您的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;
}

相关内容

  • 没有找到相关文章

最新更新