Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class ArrayStack<E> implements StackADT<E> {
- // field to refer to an array which will hold the stack elements
- protected E[] S;
- // index to top element
- protected int top = -1;
- // a constructor
- public ArrayStack(int cap) {
- S = (E[]) new Object[cap];
- // compiler may give warning, but this
- // is OK
- }
- public ArrayStack() {
- S = (E[]) new Object[10];
- }
- public int size () {
- return (top +1);
- }
- public boolean isEmpty() {
- return (top <0);
- }
- public E pop() throws EmptyStackException {
- E element;
- if (isEmpty())
- throw new EmptyStackException("Empty stack: cannot pop");
- element = S[top];
- S[top] = null; // facilitates garbage collection
- top = top - 1;
- return element;
- }
- public E top() throws EmptyStackException {
- if (isEmpty())
- throw new EmptyStackException("Stack is empty. Cannot obtain an element");
- return S[top];
- }
- public void push(E element){
- // include method body
- if (size() == top) {
- E[] ProvS = (E[]) new Object[S.length*2];
- for (int i= 0; i<S.length; i++) {
- ProvS[i] = S[i];
- }
- S = ProvS;
- ProvS = null;
- }
- top++;
- S[top]=element;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement