如何使用结构和指针推动和弹出一堆双打
How to push and pop a stack of doubles using structures and pointers
有这个任务要求我制作特定结构的项目并堆叠无限数量的项目。我还应该能够在列表顶部弹出该项目。我已经能够堆叠它们,但是当我尝试弹出我的程序时冻结。
弹出函数的规则如下: "在堆栈顶部查找项目,将其值保存到变量中,使其下一个项目成为新的堆栈顶部。使用 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;
}
相关文章:
- 在 c++ 中拥有一组结构的正确方法是什么?
- 如何使用结构和指针推动和弹出一堆双打
- 使用一组结构,避免在一组结构中出现重复的结构
- 如何改进一堆在已知值范围内评估变量的 else-if 条件?
- 当我在结构中包含多个数组时,我的程序会跳过一堆代码
- 在 c++ 中将一种结构类型分配给另一种类型
- 动态分配一维结构数组:两种方法
- 在共享指针的值中调用 std::swap 调用一堆构造函数和析构函数
- 将指向结构的指针转换为具有较少字段数的另一种结构类型
- 使用带有.lib和一堆.dll和.h文件的Python CFFI
- 用 c++ 编写一堆类似的 if 语句的漂亮方法
- 当我尝试编译程序时,我遇到了一堆错误,例如:'std::max':找不到匹配的重载函数
- Swig C++ to python:编译一堆.cpp和.h文件
- template元编程:将一堆模板参数相乘
- 一组结构缺少元素
- 在.NET中存储一堆恒定值的最佳方法
- 我的一堆函数出现"undefined reference"错误,我不知道为什么
- 制作一堆 int 数组
- 为什么glut.h会在CodeBlocks中弹出一堆未定义的引用
- 更换一堆std ::矢量条目