Get premium membership and access questions with answers, video lessons as well as revision papers.

Illustrate the change of a C++ stack so it dynamically allocates memory for the stack.Have the size of the stack specified by a parameter to...

      

Illustrate the change of a C++ stack so it dynamically allocates memory for the stack.Have the size of the stack specified by a parameter to the constructor function.(Free this memory with a destructor function)

  

Answers


Davis
//Dynamically allocated stack.
#include
#include
using namespace std;
// Declare a stack class for characters
class stack {
char *stck; //holds the stack
int tos; // index of top of stack
int size; // size of the stack
public:
stack (int s) ; //constructor
~stack(); destructor
void push ( char ch ); //push character on stack
char pop (); // pop character from stack
};
// Initialize the stack
stack::stack (int s)
{
cout << "constructing a stack\n";
tos = 0;
stck = (char *) malloc (s);
if(!stck) {
cout << "Allocating error\n";
exit (1);
}
size = s;
}
stack::~stack()
{
free(stck);
}
// Push a character.
void stack::push (char ch)
{
if(tos==size) {
cout << "stack is full\n;
return;
}
stck[tos] = ch;
tos++;
}
if (tos==0) {
cout << "Stack is empty\n";
return 0; // return null on empty stack
}
tos--;
return stck [tos];
}
int main()
{
// Create two stacks that are automatically initialized.
stack s1 (10), s2(10);
int i;
s1.push ('a');
s2.push ('x');
s1.push ('b');
s2.push ('y');
s1.push ('c');
s2.push ('z');
for (i=0; i<3; i++) cout << "pop s1: "<< s1.pop() << "\n";
for(i=0; i<3; i++) cout << "pop s2: " <return 0;
}

Githiari answered the question on May 5, 2018 at 17:48


Next: Create a C++ class called stopwatch that emulates a stopwatch that keeps track of elapse time. Use a constructor to initially set the elapse time...
Previous: Create a class C++ class called t_and_d that is passed the current system time and date as a parameter to its constructor when it is...

View More Computer Science Questions and Answers | Return to Questions Index


Learn High School English on YouTube

Related Questions