Question: Please rewrite the following code so that after the first doubling of the array, halve the size of the array if fewer than half of

Please rewrite the following code so that after the first doubling of the array, halve the size of the array if fewer than half of the arrays locations are occupied by current stack entries.

in C++

Thank you

#include using namespace std; //define the class for abstract data type //named the class ADTStack class ADTStack { //public variables declared public: //to store top index int top; //size of array initially int size = 5; //initialized with a random value 5 //initialize the array using dynamic memory allocation int *arr =(int *) malloc(size*sizeof(int)); //constructor ADTStack(){ top = -1; } //push method for stack void push(int item){ //if stack getts full if(top>=size){ //double the size size = size*2; //arrays in C++ cannot be resized to double its size //so we declare a new array with size = size *2 //and initialize it using dynamic memory allocation int *newArr = (int *)malloc(size*sizeof(int)); //copy the contents of original array to new array for(int i=0;i<=top;i++){ newArr[i] = arr[i]; } //delete the original array contents delete [] arr; //then assign new array to the original array arr = newArr; } //increment the top and push the element in stack top+=1; arr[top] = item; } //pop method of stack void pop(){ //underflow condition if(top<0){ cout<<" Underflow "; } //display popped element and decrement the top index else{ cout<<" Popped element is : "<

//main method int main() { //initialize an object of ADTStack ADTStack stack; //push and pop operations only for testing purpose stack.push(20); //pushed element 20 stack.push(30); //pushed element 20 stack.push(40); //pushed element 20 stack.push(50); //pushed element 20 stack.push(60); //pushed element 20 stack.push(70); //pushed element 20 stack.push(80); //pushed element 20 stack.display(); //display the contents of stack stack.pop(); //pop one element stack.display(); //now again display the contents of stack

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!