Step 1: Implement the methods in the Stack ADT using an array to store the stack
ID: 3650293 • Letter: S
Question
Step 1: Implement the methods in the Stack ADT using an array to store the stack elements.Stacks change in size; therefore, you need to store the array index of the topmost element in
the stack (top), along with the stack elements themselves (element). Arrays have a limited
capacity. The maximum number of elements our stack can hold can be determined by referencing
length in the array object
Explanation / Answer
public class ArrayQueue implements QueueADT { /** Elements on this. */ protected Object[] elements = new Object[10]; /** Index of front element in this. */ protected int front = -1; /** Index of back element in this. */ protected int back = -1; /** Constructs an empty queue. */ public ArrayQueue() {} /** * Enqueues the given element on this. * @param o object to enqueue */ public void enqueue(Object o) { back = after(back); elements[back] = o; if (front == -1) { front = 0; } } /** Returns the front element on this. */ public Object front() { if (isEmpty()) { throw new RuntimeException(“Queue is empty”); } return elements[front]; } /** Removes and returns the front element on this. */ public Object dequeue() { if (isEmpty()) { throw new RuntimeException(“Queue is empty”); } Object f = elements[front]; front = after(front); if (size == 0) { front = -1; back = -1; } } /** Returns the size of this. */ public int size() { if (back >= front) { return (back – front); } return (back + elements.length – front); } /** Returns whether or not this is empty. */ public boolean isEmpty() { return (size() == 0); } /** * Returns the array index after the given index. * @param i index in the array */ private int after(int i) { return ((i + 1) % elements.length); } }
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.