[TOC]
# 分析
~~~
stack<E>
void push(E) 添加一个元素,入栈
E pop() 拿出一个元素,出栈
E peek() 看下栈顶的元素是谁
int getSize() 查看大小
boolean isEmpty() 栈是否为空
~~~
# 代码实现
## 接口
~~~
public interface Stack<E> {
int getSize();
boolean isEmpty();
void push(E e);
E pop();
E peek();
}
~~~
## 实现类
~~~
public class ArrayStack<E> implements Stack<E> {
//基于之前写的动态数组
Array<E> array;
public ArrayStack(int capacity) {
array = new Array<E>(capacity);
}
public ArrayStack() {
array = new Array<E>();
}
//获取容量
public int getCapacity() {
return array.getCapacity();
}
@Override
public int getSize() {
return array.getSize();
}
@Override
public boolean isEmpty() {
return array.isEmpty();
}
@Override
public void push(E e) {
//往动态数组中
array.addLast(e);
}
@Override
public E pop() {
//删除最后一个元素
return array.removeLast();
}
@Override
public E peek() {
return array.getLast();
}
@Override
public String toString() {
StringBuilder res = new StringBuilder();
res.append("Stack: ");
res.append('[');
for (int i = 0; i < array.getSize(); i++) {
res.append(array.get(i));
if (i != array.getSize() - 1) {
res.append(", ");
}
}
//top处就是栈顶
res.append("] top");
return res.toString();
}
}
~~~
## 测试
~~~
public class TestStack {
public static void main(String[] args) {
ArrayStack<Integer> stack = new ArrayStack<Integer>();
for (int i = 0; i < 5; i++) {
stack.push(i);
System.out.println(stack);
}
stack.pop();
System.out.println(stack);
}
}
~~~