In: Computer Science
You will write Stack class in c++ that will be integrated into a larger software product provided by the instructor. This Stack class uses a dynamically allocated array to store data values (integers) that have been pushed onto the stack object. When the client code attempts to push another integer onto a full stack, your Push operation should invoke the Resize() function which attempts to double the capacity of the stack and then add the new data value to the resized stack array. In Resize() a new array (that holds twice as many integers) is dynamically allocated, data from the old stack array is copied into the new larger stack array, the old stack array is deallocated, and the new data value is pushed onto the new array.
ANS:
//STACK HEADER
class Stack
{
private:
int* stackArray;
int StackSize;
int top;
public:
Stack(int);
~Stack();
void push(int);
void pop(int&);
bool isFull();
bool isEmpty();
void reSizeStack(int item);
int sizeOfStack();
void printStack();
};
//STACK CPP
#include "Stack.h"
#include<iostream>
using namespace std;
Stack::Stack(int len)
{
stackArray = new int[len];
StackSize = len;
top = -1;
}
Stack::~Stack()
{
delete[] stackArray; // deleteing stack dynamic array
after program completion
}
void Stack::push(int item)
{
if (isFull())
{
cout << "Stack is Full"
<< endl;
cout << "Resize Stack"
<< endl;
reSizeStack(item);
}
else
{
top += 1;
stackArray[top] = item;
cout << "Element Added in
stack" << endl;
}
}
void Stack::pop(int& num)
{
if (isEmpty())
{
cout << "Stack is Empty"
<< endl; // If empty then only cout else pop
}
else
{
num = stackArray[top];
top--;
}
}
void Stack::reSizeStack(int item)
{
int oldSize = StackSize;
int* oldStack = new int[StackSize];
StackSize = StackSize * 2;
//Copying old stack data to new stack
for (int i = 0; i < oldSize; i++)
{
oldStack[i] = stackArray[i];
}
stackArray = new int[StackSize];
//Copying Old data into StackArray and new element too
for (int i = 0; i < oldSize; i++)
{
stackArray[i] = oldStack[i];
}
//Inserti\ng new element
push(item);
}
bool Stack::isFull()
{
if (top == StackSize - 1)
{
return true; // If top is equal to
end of array then it is full so return true
}
else
{
return false;
}
}
bool Stack::isEmpty()
{
if (top == -1)
{
return true; //if top=-1 it means
no element in stack so empty
}
else
{
return false;
}
}
int Stack::sizeOfStack()
{
return StackSize;
}
void Stack::printStack()
{
cout << "Visiting Stack and printing each
element" << endl;
int element;
for (int i = 0; i < StackSize; i++)
{
pop(element);
cout << "Element#" << i
<< "=" << element << endl;
}
}
int main()
{
Stack obj(3);
cout << "Enter elements of Stack" << endl;
int element;
for (int i = 0; i < 3; i++)
{
cout << "Enter element#"
<< i + 1 << endl;
cin >> element;
obj.push(element);
}
obj.push(10);
obj.printStack();
}
Comment down for any queries
Please give a thumbs up if you are satisfied with answer
:)