先定义一个接口
public interface Stack<E> {
int getSize();
boolean isEmpty();
boolean contains(E e);
//入栈
void push(E e);
//查看栈顶的数据
E peek();
//出栈
E pop();
}
再定义一个栈的实现类,实现上述接口
/**
* 基于数组实现栈
* @author hcc
*
*/
public class HArrayStack<E> implements Stack<E> {
private HGenericityArrayList<E> data;
public HArrayStack() {
data = new HGenericityArrayList<E>();
}
public HArrayStack(int capacity) {
data = new HGenericityArrayList<E>(capacity);
}
public int getCapacity() {
return data.getCapacity();
}
@Override
public int getSize() {
// TODO Auto-generated method stub
return data.getSize();
}
@Override
public boolean isEmpty() {
// TODO Auto-generated method stub
return data.isEmpty();
}
@Override
public boolean contains(E e) {
// TODO Auto-generated method stub
return data.contains(e);
}
@Override
public void push(E e) {
// TODO Auto-generated method stub
data.add(e);
}
@Override
public E peek() {
// TODO Auto-generated method stub
return data.get(data.getSize()-1);
}
@Override
public E pop() {
// TODO Auto-generated method stub
return data.remove(data.getSize()-1);
}
@Override
public String toString() {
StringBuilder str = new StringBuilder();
str.append("HArrayStack:");
str.append(data);
return str.toString();
}
}
网友评论