版权声明: https://blog.csdn.net/qq_39769369/article/details/83310283
设计:
1、该数组存储对象类型在实例化是才确定-----泛型
2、数组的索引0是栈底
3、创建一个正整数变量top ----是栈顶元素否后的索引号
4、创建一个栈的接口----定义如下函数:
代码实现:
接口类:StackADT
public interface StackADT <T> {
/**
* 压栈
* @param t
*/
public void push(T t);
/**
* 弹栈
* 弹出栈顶元素,并移除
* @return
* @throws EmptyCollectionException
*/
public T pop() throws EmptyCollectionException;
/**
* 弹出栈顶元素不移除
* @return
* @throws EmptyCollectionException
*/
public T peek() throws EmptyCollectionException;
/**
* 判断栈是否为空
* @return
*/
public boolean isEmpty();
/**
* 栈当前存储的大小
* @return
*/
public int size();
public String toString();
}
实现类:ArrayStack
/**
* 用数组创建栈
*
* @author Administrator
*
* @param <T>
*/
public class ArrayStack<T> implements StackADT<T> {
// 常量---存储容量
private final int DEFAULT_CAPACITY = 100;
// 栈顶表示 栈底----0
private int top;
private T[] stack;
/**
* 默认容量
*/
@SuppressWarnings("unchecked")
public ArrayStack() {
top = 0;
stack = (T[]) new Object[DEFAULT_CAPACITY];
}
/**
* 指定容量
*
* @param initCapacity
*/
@SuppressWarnings("unchecked")
public ArrayStack(int initCapacity) {
top = 0;
stack = (T[]) new Object[initCapacity];
}
@Override
public void push(T t) {
// 先判断数组是否已经满了
if (size() == stack.length) {
// 进行扩容
expandCapacity();
}
stack[top] = t;
top++;
}
/**
* 为数组扩容,实际就是 新建一个数组在将原来数据进行复制
*/
private void expandCapacity() {
stack = Arrays.copyOf(stack, stack.length * 2);
}
@Override
public T pop() throws EmptyCollectionException {
// 判断数组是否为空
if (isEmpty()) {
throw new EmptyCollectionException("Stack");
}
T result= stack[top - 1];
stack[top-1]=null;//弹出的值设置为null
top--;//减少top计数器
return result;
}
@Override
public T peek() throws EmptyCollectionException {
// 判断数组是否为空
if (isEmpty()) {
throw new EmptyCollectionException("Stack");
}
return stack[top - 1];
}
@Override
public boolean isEmpty() {
if (size() == 0) {
return true;
}
return false;
}
@Override
public int size() {
return top;
}
/**
* 测试
* @param args
*/
public static void main(String[] args) {
StackADT<String> strs=new ArrayStack<String>();
try {
strs.push("zhong");
String str=strs.peek();
System.out.println("strs.peek():"+str+" size:"+strs.size());
String str2=strs.pop();
System.out.println("strs.pop():"+str2+" size:"+strs.size());
} catch (EmptyCollectionException e) {
e.printStackTrace();
}
}
}
异常类:EmptyCollectionException
public class EmptyCollectionException extends Exception {
public EmptyCollectionException(String message) {
super("The "+message+ " is empty.");
}
}
扫描二维码关注公众号,回复:
3924516 查看本文章