Modify the Stack class given in the book in order for it to store double numbers
ID: 3797561 • Letter: M
Question
Modify the Stack class given in the book in order for it to store double numbers (instead of void* pointers). Add a destructor that will delete all the stack by making calls to pop(), and for each element destroyed the element will be printed to the output. Now add two constructors: the default one that will create an empty stack, and another one that will receive an integer n and will build a stack of n elements, such that the first element is 1.0, and the next ones are incremented of 0.1. Upload your Stack class. It will be then tested for correctness with stacks.cpp.
Stack.h:
//: C05:Stack2.h
// Nested structs via linked list
#ifndef STACK2_H
#define STACK2_H
class Stack
{
struct Link {
void* data;
Link* next;
void initialize(void* dat, Link* nxt);
}* head;
public:
void initialize();
void push(void* dat);
void* peek();
void* pop();
void cleanup();
};
#endif // STACK2_H ///:~
Stack.cpp:
Sample Output:
2 1.5 1 0.5
1.3 1.2 1.1 1 end.
Explanation / Answer
Hi, Please find my implemntation;
Please let me know in case of any issue.
//: C05:Stack2.h
// Nested structs via linked list
#ifndef STACK2_H
#define STACK2_H
#include <iostream>
#include <cstdlib>
using namespace std;
class Stack
{
struct Link {
double data;
Link* next;
void initialize(double dat, Link* nxt){
data = dat;
next = nxt;
}
};
Link *head;
public:
Stack(){
head = NULL;
}
Stack(int n){
for(double i=1; i<=n; i= i+ 0.1){
push(i);
}
}
~Stack(){
if(head != NULL){
while(head != NULL){
cout<<head->data<<" ";
Link *temp = head;
head = head->next;
delete temp;
}
cout<<endl;
}
}
void initialize(){
head = NULL;
}
void push(double dat){
Link *newNode = new Link;
newNode->initialize(dat, head);
head = newNode;
}
double peek(){
if(head == NULL){
cout<<"Stack is Empty!!!"<<endl;
return -1;
}
return head->data;
}
double pop(){
double d = -1;
if(head != NULL){
Link *temp = head;
d = temp->data;
head = head->next;
delete temp;
}else{
cout<<"Stack is Empty!!!"<<endl;
}
return d;
}
void cleanup(){
while(head != NULL)
cout<<pop()<<" ";
cout<<endl;
}
};
#endif // STACK2_H
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.