Question
Upgrade ResizingArrayStack class Start with ResizingArrayStack.java (generic version). Create two stacks for storing integer numbers in the test client. The first stack should have even
Upgrade ResizingArrayStack class
Start with ResizingArrayStack.java (generic version).
Create two stacks for storing integer numbers in the test client. The first stack should have even numbers and the second stack should have odd numbers.
Create a situation that you make the array capacity by half when you have current numbers with one-fourth the capacity for both stack.
_____________________________________________________________________________________
ResizingArrayStack
import edu.princeton.cs.algs4.StdOut; import java.util.NoSuchElementException;
public class ResizingArrayStack
/** * Initializes an empty stack. */ public ResizingArrayStack() { a = (Item[]) new Object[2]; n = 0; }
/** * Returns the number of items in the stack. */ public int size() { return n; }
// resize the underlying array holding the elements private void resize(int capacity) { assert capacity >= n;
Item[] temp = (Item[]) new Object[capacity]; for (int i = 0; i < n; i++) { temp[i] = a[i]; } a = temp;
}
/** * Adds the item to this stack. */ public void push(Item item) { if (n == a.length) resize(2*a.length); // double size of array if necessary a[n++] = item; // add item }
/** * Removes and returns the item most recently added to this stack. */ public Item pop() { if (n == 0) throw new NoSuchElementException("Stack underflow"); Item item = a[n-1]; a[n-1] = null; // to avoid loitering n--; // shrink size of array if necessary if (n > 0 && n == a.length/4) resize(a.length/2); return item; }
// Test Client public static void main(String[] args) { ResizingArrayStack
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started