Instructions
Requirements and Specifications
- Stack.java
- Main.java
- Get experience using Stacks.
- Get experience creating custom classes.
- Get experience with loops.
- Experience with the java.util.Random class.
Source Code
/**
* This is a stack data structure. It stores elements in a first-in-last-out
* or last-in-first-out fashion.
*
* @author Yourname
*/
public class Stack {
/**
* An array that holds the elements of the stack. The last available
* non-empty index is the top of the stack.
*/
private String[] elements;
/**
* Keep track the size of the stack and at the same time the reference to
* the top index of the stack.
*/
private int size;
/**
* Create a stack with an initial capacity.
*
* @param capacity Starting capacity of the stack
*/
public Stack(int capacity) {
elements = new String[capacity];
size = 0;
}
/**
* Put an element on top of the stack. If the stack is full, then the
* storage will be expanded.
*
* @param element Element to add on top of stack
*/
public void push(String element) {
if (size >= elements.length) {
// Increase the size if it's out of space
String[] temp = new String[elements.length * 2];
System.arraycopy(elements, 0, temp, 0, elements.length);
elements = temp;
}
// Finally, put it on top of stack and update the size.
elements[size++] = element;
}
/**
* Remove the top element.
*
* @return Top element or null if the stack is empty
*/
public String pop() {
// Nothing to pop if the stack is empty
if (isEmpty()) {
return null;
}
// Remove the top of stack to return and update the size accordingly.
return elements[--size];
}
/**
* Check if stack is empty.
*
* @return true if stack is empty, otherwise false
*/
public boolean isEmpty() {
return size == 0;
}
}