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 { private Item[] a; // array of items private int n; // number of elements on stack

/** * 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 stack = new ResizingArrayStack(); stack.push(1); StdOut.println(stack.pop()); } }

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!