There's this assignment that requires me to make items of a specific structure and stack an unlimited number of them. I should also be able to pop the item at the top of the list. I've been able to stack them but when I attempt to pop my program freezes.
The rules for the pop function are as follows: "Finds the item at the top of the stack, saves its value to a variable, makes its next item the new stack top. uses the delete operator to return its memory back to the operating system, decrements stack size by 1, and returns its saved value. If the stack is empty, it returns the constant variable HUGE_VAL which is defined in the header file. It's critical that you get the value of the popped item before you delete it; don't access the value of an already-deleted item."
I'm also having an issue with HUGE_VAL, it's advising me that it is undefined even though it is a constant from one of the imports. Below is my code:
Please advise me as to what I might be doing wrong
#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);
}