ArrayStack继承于ArrayList。栈顶是最后一个入栈的元素既是链的尾,栈底是第一个入栈元素既是链头。
peek()方法:返回栈的顶部元素但不移除它(返回最后一个元素);
public Object peek() throws EmptyStackException {
int n = size();
if (n <= 0) {
throw new EmptyStackException();
} else {
return get(n - 1);
}
}
peek(int n)方法:从栈顶(以下标为0)开始取出下标元素;通俗讲,以最后一个元素的下标为0,从后向前取值;
public Object peek(int n) throws EmptyStackException {
int m = (size() - n) - 1;
if (m < 0) {
throw new EmptyStackException();
} else {
return get(m);
}
}
pop()方法:取出栈顶的值并从栈中移除(最后一个元素),返回移除的元素;
public Object pop() throws EmptyStackException {
int n = size();
if (n <= 0) {
throw new EmptyStackException();
} else {
return remove(n - 1);
}
}
push(Object item)方法:向栈中压入数据(添加数据到集合中),并返回添加的元素;
public Object push(Object item) {
add(item);
return item;
}
search(Object object)方法:从栈中查询指定元素,返回其下标;
public int search(Object object) {
int i = size() - 1; // Current index
int n = 1; // Current distance
while (i >= 0) {
Object current = get(i);
if ((object == null && current == null) ||
(object != null && object.equals(current))) {
return n;
}
i--;
n++;
}
return -1;
}
get()方法:返回栈的顶部元素(最后一个元素);
public Object get() {
int size = size();
if (size == 0) {
throw new BufferUnderflowException();
}
return get(size - 1);
}
remove()方法:移除栈的顶部元素(最后一个元素),并返回该元素;
public Object remove() {
int size = size();
if (size == 0) {
throw new BufferUnderflowException();
}
return remove(size - 1);
}