Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

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

image text in transcribed

image text in transcribed

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 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

voidPointers.cpp

 #include  #include "Stack.h" using namespace std; void delete_func(void * pt){ double * dpt = (double *)pt; coutinitialize(); double value; int n; cin >> n; for (int i=0; i > value; doubleStack->push(new double(value)); } void (*del_func_ptr)(void * pt) = delete_func; doubleStack->setDeleteCallback(del_func_ptr); doubleStack->cleanup(); return 0; }
One of the problems of our Stack and LinkedList structs is that if we make them handle generic types with void* pointers, they will not know how to delete the elements we insert in them. We will see later how templates will solve that, but for now let's practice using pointers to functions. Extend the book's Stack struct with one more member variable that will hold a pointer to the following function prototype: void deletecb (void *pt) You will then add a member function to set this pointer: void Stack::setDeleteCallback(void (#delcb) (void * pt)) After you do this, then add the corresponding code in the cleanup method to traverse all elements of the stack, deleting the links and calling the delete callback once for each stored void pointer. The user will be responsible for providing the delete callback and implementing it with the correct delete call after converting the void pointer argument to its correct type. You may download the Stack.h file, make the modifications described above and submit it. Your code will be evaluated using voidPointers.cpp. Input 3 11 -4 2 Output Deleting: 2 Deleting: -4 Deleting: 11

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Questions Exercises Problems And Cases For Financial Accounting

Authors: Antle

2nd Edition

032418459X, 978-0324184594

Students also viewed these Databases questions