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
{
arr = new X[size];
capacity = size;
t = -1;
}
template
void ArrayStack
{
if (isFull())
{
cout << "OverFlow Program Terminated ";
exit(EXIT_FAILURE);
}
cout << "Inserting" << x << endl;
arr[++t] = x;
}
template
X ArrayStack
{
if (empty())
{
cout << "UnderFlow Program Terminated ";
exit(EXIT_FAILURE);
}
cout << "Removing " << top() << endl;
return arr[t--];
}
template
X ArrayStack
{
if (!empty())
return arr[t];
else
exit(EXIT_FAILURE);
}
template
int ArrayStack
{
return t + 1;
}
template
bool ArrayStack
{
return t == -1;
}
template
bool ArrayStack
{
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.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
Get step-by-step solutions from verified subject matter experts
