

















Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!


















0 1 2 3 4 5 6
a b c d e
0 1 2 3 4 5 6
a b c d e
a b c d e
null
firstNode
peek() => get(0) O(1) time push(theObject) => add(0, theObject) O(1) time pop() => remove(0) O(1) time Docsity.com
a b c d e
null
firstNode
/** create a stack with the given initial
public DerivedArrayStack(int initialCapacity)
{super(initialCapacity);}
/** create a stack with initial capacity 10 */
public DerivedArrayStack()
{this(10);}
public boolean empty()
{return isEmpty();}
public Object peek()
{
if (empty()) throw new EmptyStackException(); return get(size() - 1)
}
0 1 2 3 4 5 6
a b c d e
Code for derived class is quite simple and easy to develop. Code is expected to require little debugging. Code for other stack implementations such as a linked implementation are easily obtained.
get(0) … get bottom element remove(5) add(3, x) So we do not have a true stack implementation. Must override undesired methods.
public Object get(int theIndex) {throw new UnsupportedOperationException();} Change earlier use of get(i) to super.get(i). Docsity.com
if (empty())
throw new EmptyStackException(); return remove(size() - 1);
vs.
try {return remove(size() - 1);}
catch(IndexOutOfBoundsException e)
{throw new EmptyStackException();}
package dataStructures;
import java.util.EmptyStackException;
import utilities.*; // ChangeArrayLength
public class ArrayStack implements Stack
{
// data members int top; // current top of stack Object [] stack; // element array // constructors come here // Stack interface methods come here
}
public ArrayStack(int initialCapacity)
{
if (initialCapacity < 1) throw new IllegalArgumentException ("initialCapacity must be >= 1"); stack = new Object [initialCapacity]; top = -1;
}
public ArrayStack()
{this(10);}