Question: Write a Java program that implements a stack using an array. You can use the code from the program below (which was written in C++)

Write a Java program that implements a stack using an array. You can use the code from the program below (which was written in C++) as a guideline. Demonstrate your program works using your main function.

#include

#include

using namespace std;

#define DEF_CAPACITY 10

template

class stack

{

X *arr;

int t;

int capacity;

public:

ArrayStack(int size = DEF_CAPACITY);

void push(X);

X pop();

X top();

int size();

bool empty();

bool isFull();

};

template

ArrayStack::ArrayStack(int size)

{

arr = new X[size];

capacity = size;

t = -1;

}

template

void ArrayStack::push(X x)

{

if (isFull())

{

cout << "OverFlow Program Terminated ";

exit(EXIT_FAILURE);

}

cout << "Inserting" << x << endl;

arr[++t] = x;

}

template

X ArrayStack::pop()

{

if (empty())

{

cout << "UnderFlow Program Terminated ";

exit(EXIT_FAILURE);

}

cout << "Removing " << top() << endl;

return arr[t--];

}

template

X ArrayStack::top()

{

if (!empty())

return arr[t];

else

exit(EXIT_FAILURE);

}

template

int ArrayStack::size()

{

return t + 1;

}

template

bool ArrayStack::empty()

{

return t == -1;

}

template

bool ArrayStack::isFull()

{

return t == capacity - 1;

} void grow(double pt[], int size)

{

int newsize = size * 2;

for(int t= 0; t

{

pt[t+size] = pt[t];

}

cout<<"twice of the array is: "<

for(int t=0;t

{

cout<

}

cout<

}

int main()

{

ArrayStack pt(2);

pt.push("Bob");

pt.push("Alice");

pt.top();

pt.pop();

pt.push("Eve");

cout << "Top element is " << pt.top() << endl;

cout << "ArrayStack size is " << pt.size() << endl;

cout<< "ArrayStack new size is "<

pt.pop();

if (pt.empty())

cout << "ArrayStack Is Empty ";

else

cout << "ArrayStack Is Not Empty ";

grow(pt,newsize)

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!