Thursday, March 23, 2017
Design a Stack using Array with certain capacity
valid stack range [0, head)
public MyStack<E> {
private final int CAPACITY = 10;
private int head;
private E[] array;
public MyStack(int capacity) {
this.array = new E[capacity];
this.head = 0;
}
public MyStack() {
this(CAPACITY);
}
public boolean empty() {
return head == 0;
}
public boolean push(E element) {
if (head >= array.length) return false;
array[head++] = element;
return true;
}
public E pop() {
if (head == 0) return null;
return array[--head];
}
public E peek() {
//if (head == 0) return null;
//return array[head - 1];
return (head == 0) ? null : array[head - 1];
}
}
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment