Question: Constructors/Destructors Extend the Stack.h class given in order for it to store double numbers (instead of void* pointers). Add a destructor that will delete all

Constructors/Destructors

Extend the Stack.h class given 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 by 0.1. Upload your Stack class, which will be tested for correctness with stacks.cpp.

SAMPLE OUTPUT s1 2 1.5 1 0.5 s2 1.3 1.2 1.1 1 end

Stack.h

#ifndef STACK_H

#define STACK_H

#include

struct Stack {

struct Link {

void* data;

Link* next;

void initialize(void* dat, Link* nxt) {

data = dat;

next = nxt;

}

}* head;

void initialize() {

head = 0;

}

void push(void* dat) {

Link* newLink = new Link;

newLink->initialize(dat, head);

head = newLink;

}

void* peek() {

if (head == 0) {

std::cout << "Stack is empty";

}

return head->data;

}

void* pop() {

if(head == 0)

return 0;

void* result = head->data;

Link* oldHead = head;

head = head->next;

delete oldHead;

return result;

}

void cleanup() {

if (head == 0){

std::cout << "Stack is empty";

}

else {

std::cout << "Stack is not empty";

}

}

};

#endif

stacks.cpp

#include

#include "Stack.h"

using namespace std;

int main(int argc, const char * argv[])

{

cout << "s1 ";

{

Stack s1;

for( int i = 1; i < 5; i++ )

s1.push( double(i)/2.0 );

}

cout << endl;

cout << "s2 ";

{

Stack s2(4);

}

cout << " end ";

return 0;

}

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!