Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

(1) Implementing a stack that uses a dynamically allocated array to represent st

ID: 3630330 • Letter: #

Question


(1) Implementing a stack that uses a dynamically allocated array to represent stack items. In the constructor you allocate an array of certain size (the size can be passed as a value to the constructor such that users can created an stack of certain size. If no size is specified, use a default size of 100. For example:
class Stack {
...
}

Stack stackA; // define an stack object of default size of 100 elements
Stack stackB(200); // define an stack object of 200 maximum number of elements

You need to provide a copy constructor and a destructor (in order to release the array when the stack object is no longer needed).

Write some test cases to verify your implementation is correct.

Explanation / Answer

#include <iostream>

#include <malloc.h>

using namespace std;

class Stack

{

private:

int *items; //dynamic array

int top; //stack pointer

int size; //size of the stack

public:

Stack(); //default constructor

Stack(int size);

Stack(Stack &copy); //copy constructor

void push(int element);

int pop();

int getTop();

bool isEmpty();

bool isFull();

void display();

~Stack(); //distructor

};

//default constructor

Stack::Stack()

{

Stack(20);

}

//constructor takes the array size

Stack::Stack(int sz)

{

items = new int[sz];

size = sz;

top = -1;

}

//copy constructor

Stack::Stack(Stack &copy)

{

items = new int[copy.size];

for(int i=0;i <= copy.top;i++)

this->push(copy.items[i]);

}

//inserts an element into the stack

void Stack::push(int element)

{

if(!isFull())

items[++top] = element;

else

cout<<"stack is full"<<endl;

}

//pops an element from the stack

int Stack::pop()

{

int element = getTop();

top--;

return element;

}

//gets the top element of the stack

//without removing it from the stack

int Stack::getTop()

{

if(!isEmpty())

return items[top];

else

return NULL;

}

//checks whether stack is empty or not

bool Stack::isEmpty()

{

return (this->top == -1);

}

//checks whether stack is full or not

bool Stack::isFull()

{

return (this->top >= this->size -1);

}

//distructor to deallocate the memory

Stack::~Stack()

{

delete []items;

items = NULL;

}

//displasy atsck elements to the screen

void Stack:: display()

{

for(int i =0; i<=top;i++)

cout<<items[i]<< " ";

}

//main function

int main()

{

Stack A;

Stack B(20);

A.push(125);

A.push(458);

A.push(412);

A.push(758);

cout<<"Stack A contains: "<<endl;

A.display();

Stack C(A);

cout<<"Copied A to C: "<<endl;

C.display();

cout<<"Popping from A: "<<A.pop()<<endl;

cout<<"Popping from A: "<<A.pop()<<endl;

cout<<"Popping from A: "<<A.pop()<<endl;

cout<<"Stack A contains: "<<endl;

A.display();

cout<<"C contains: "<<endl;

C.display();

return 0;

}