Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

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

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_2

Step: 3

blur-text-image_3

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

Real Time Database Systems Architecture And Techniques

Authors: Kam-Yiu Lam ,Tei-Wei Kuo

1st Edition

1475784023, 978-1475784022

More Books

Students also viewed these Databases questions