In: Computer Science
void Stack :: push(float x)
{
if (count _______
capacity)
// If there is no room for a new value
{
float* new_A = ______ float[ 2 * ________
];
// Create a new array with two-fold capacity
for (int i = 0; i < count;
++i) //
Copy existing data to new array
_______= A[i];
delete[]__________
; //
Delete old array
A =
new_A; //
Connect to the new array
capacity *= _______
;
// Update the capacity
}
A[ ______] =
x;
// Insert the new item onto the stack
++ ________
;
// Update count of items in the stack
}
In case of any query do comment. Thanks
Answer:
void Stack :: push(float x)
{
if (count == capacity) // If there is no room for a new value
{
float* new_A = new float[ 2 * capacity ]; // Create a new array with two-fold capacity
for (int i = 0; i < count; ++i) // Copy existing data to new array
new_A[i]= A[i];
delete[] A ; // Delete old array
A = new_A; // Connect to the new array
capacity *= 2 ; // Update the capacity
}
A[count] = x; // Insert the new item onto the stack
++ count; // Update count of items in the stack
}
Explanation:
Check count == capacity for stack is full or there is no room for new element to push
Declare a new array of the size double of the capacity. (float* new_A = new float[ 2 * capacity ];)
Copy the existing array to new array index wise till count -1 index using for each loop:
for (int i = 0; i < count; ++i) // Copy existing data to new
array
new_A[i]= A[i];
delete[] is used top delete memory created by existing array which was initialized using new operator.
hence delete[] A ;
Then double the capacity:
capacity *= 2 ;
to insert the new item , we have to use count variable which is tracking the current index:
A[count] = x;
now increase the value of count variable by 1:
++ count;