Java Floodit game public class GenericArrayStack<E> implements Stack<E> { privat
ID: 3804766 • Letter: J
Question
Java Floodit game
public class GenericArrayStack<E> implements Stack<E> {
private E[] elems;
private int top;
@SuppressWarnings( "unchecked" )
public GenericArrayStack( int capacity ) {
elems = (E[]) new Object[ capacity ];
top = 0;
}
public boolean isEmpty() {
return top == 0;
}
public void push( E elem ) {
elems[ top ] = elem;
top++;
}
public E pop() {
E saved;
top--;
saved = elems[ top ];
elems[ top ] = null;
return saved;
}
public E peek() {
return elems[ top-1 ];
}
}
Explanation / Answer
import java.util.NoSuchElementException; /** * The class GenericLinkedStack represents the linked stack data structure. * It supports four operations: isEmpty, push, peek, and pop. * The elements of this linked stack are of type Elem, which is defined in an inner class of GenericLinkedStack. */ public class GenericLinkedStack implements Stack4 { /** * The static class Elem represents a node of the linked stack data structure. * It has references to its payload (info) and its next value (next). */ private static class Elem { private E info; private Elem next; private Elem(E info, Elem next) { if(info == null){ throw new NullPointerException("Attempting to set payload to null."); } this.info = info; this.next = next; } } /** * top element of the GenericLinkedStack. */ private Elem top; /** * Tests if this GenericLinkedStack is empty. * * @return true if this GenericLinkedStack is empty; and false otherwise. */ public boolean isEmpty() { return (top == null); } /** * Puts an element onto the top of this GenericLinkedStack. * * @param info the element be put onto the top of this GenericLinkedStack. */ public void push(T info) { if (info == null){ throw new NullPointerException("The element being pushed to the stack is null"); } Elem previousTop = top; top = new Elem(info, previousTop); } /** * Returns a reference to the top element; does not change * the state of this GenericLinkedStack. * * @return The top element of this GenericLinkedStack without removing it. */ public T peek() { if (isEmpty()) { throw new EmptyStackException2("Stack is empty"); } return top.info; } /** * Removes and returns the element at the top of this GenericLinkedStack. * * @return The top element of this GenericLinkedStack. */ public T pop() { if (isEmpty()) { throw new EmptyStackException2("Stack is empty"); } T saved = top.info; top = top.next; return saved; } }Related Questions
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.