In: Computer Science
Provide an array-based implementation of stack that allows us adding (pushing) items regardless of the capacity. That means, when the stack becomes full, it doubles its capacity to be able to hold more items. Specifically, in your implementation start with default capacity 4, when the stack reaches 4 items and you want to add more, make the capacity 8, and so on. Therefore, you can always add items and the stack expands.
Name the class ImprovedStack and implement the following methods in addition to two constructors, one default no-args constructor, and one constructor that sets the initial capacity.
int pop()
void push(int item)
int peek()
int size()
boolean isEmpty()
boolean isFull()
Assume your items are of type int. your file to be submitted to Gradescope should be named ImprovedStack.java.
//Working Code :-
public class HelloWorld {
static final int capacity = 4;
static int top = -1;
static int size = 0;
static int[] a;
static int[] size_doubles(int[] a)
{
int[] new_a = new int[size + capacity];
for (int i = 0; i < size; i++)
new_a[i] = a[i];
size += capacity;
return new_a;
}
static void push(int ele)
{
if (top == size - 1)
a = size_doubles(a);
a[++top] = ele;
}
static void pop()
{
top--;
}
static void display(int[] a)
{
if (top == -1)
System.out.println("Stack is full Empty");
else
{
System.out.print("Stack: ");
for (int i = top ; i >= 0; i--)
System.out.print(a[i] + " ");
System.out.println();
}
}
static boolean isEmpty(){
if (top == -1)
return true;
else
return false;
}
static boolean isFull(){
if (top == size-1)
return true;
else
return false;
}
static int peak (int [] a){
return a[top];
}
public static void main(String args[])
{
a = size_doubles(new int[size + capacity]);
if(isEmpty())
System.out.println("Stack is Empty");
push(11);
push( 21);
push(31);
push(41);
display(a);
if(isFull())
System.out.println("Stack is full ");
pop();
display(a);
System.out.println("peak is "+peak(a));
}
}
//Output :-
//Comments : Intially stack would be empty l , so it should display empty and after inserting 4 elements it should display full , peak element is the top element or the recenly pushed element .