Answers to Self-Study Questions

Test Yourself #1

public ArrayStack() {
    items = (E[])(new Object[INITSIZE]);
    numItems = 0;
}

It might seem like items should be initialized as follows:

items = new E[INITSIZE];

However, Java does not allow you create a new array using generic type so what we'll do is create an array of Objects and cast it to an array of items of type E

Test Yourself #2

public E pop() throws EmptyStackException {
    if (numItems == 0) {
        throw new EmptyStackException();
    }
    else {
        numItems--;
        return items[numItems];
    }
}

Test Yourself #3

Operation Worst-case Time Average-case Time
constructor

O(1)

O(1)

isEmpty

O(1)

O(1)

push

O(N)

O(1)

pop

O(1)

O(1)

peek

O(1)

O(1)

Test Yourself #4

public void push(E ob) {
    items = new Listnode<E>(ob, items);
    numItems++;
}

Test Yourself #5

Operation Worst-case Time
constructor

O(1)

isEmpty

O(1)

push

O(1)

pop

O(1)

peek

O(1)

Test Yourself #6

public static void reverseQ(QueueADT<E> q) {
// precondition: q contains x1 x2 ... xN (with x1 at the front)
// postcondition: q contains xN ... x2 X1 (with xN at the front)
    StackADT<E> s = new ArrayStack<E>();
    while (!q.empty()) {
        s.push(q.dequeue());
    }
    while (!s.empty()) {
        q.enqueue(s.pop());
    }
}