自定义数组实现栈的结构。
package test; public class MyArrayStackClient {
public static void main(String[] args) {
ArrayStack<Integer> stack = new ArrayStack<Integer>();
// ArrayStack<Integer> stack=new ArrayStack<Integer>();
// 入栈
stack.push(6);
stack.push(5);
stack.push(4);
stack.push(3);
stack.push(2);
stack.push(1); System.out.println("此时栈是否为空:" + stack.isEmpty());// 判断栈是否为空
System.out.println("获取栈顶元素: " + stack.peek());// 获取栈顶元素
System.out.println("当前栈内元素共有: " + stack.size() + "个");
System.out.println("元素: " + stack.pop() + "出栈");// 元素出栈
System.out.println("当前栈内元素共有: " + stack.size() + "个");
stack.clear();
System.out.println("当前栈内元素共有: " + stack.size() + "个"); }
}
package test; public class ArrayStack<T> implements IStack<T> {
private final int DEFAULT_SIZE = 3;
private int size = 0;
private int capacity = 0; // top指向下一个能够添加元素的位置
private int top = 0;
private Object[] array; public ArrayStack() {
this.capacity = this.DEFAULT_SIZE;
this.array = new Object[this.capacity];// 初始栈
this.size = 0;
} public ArrayStack(int capacity) {
this.capacity = capacity;
this.array = new Object[this.capacity];
this.size = 0;
} // 栈中元素为空
@Override
public boolean isEmpty() {
// TODO Auto-generated method stub
return size == 0;
} // 获取栈顶元素
@Override
public T peek() {
// TODO Auto-generated method stub
return (T) this.array[this.top - 1];
} @Override
public T pop() {
// TODO Auto-generated method stub
T element = (T) this.array[top - 1];
this.array[top - 1] = null;
this.size--;
return element;
} // 元素入栈
@Override
public void push(T element) {
// TODO Auto-generated method stub
if (this.size < this.capacity) {
this.array[top] = element;
this.top++;
this.size++;
} else {
// System.out.println("out of array");
enlarge(); // 扩大栈的容量
push(element);
}
} // 扩大栈的容量
public void enlarge() {
this.capacity = this.capacity + this.DEFAULT_SIZE;
Object[] newArray = new Object[this.capacity];
// System.arraycopy(array, 0, newArray, 0, array.length);
arrayCopy(array, newArray);
fillArray(array, null); // 用null将array填满
this.array = newArray;
} // 复制元素
public void arrayCopy(Object[] array, Object[] newArray) {
for (int i = 0; i < array.length; i++) {
newArray[i] = array[i];
}
} // 向数组中装填元素
public void fillArray(Object[] array, Object val) {
for (int i = 0; i < array.length; i++) {
array[i] = val;
}
} // 求出此时栈中元素的大小
public int size() {
return this.size;
} // 清空栈
@Override
public void clear() {
// TODO Auto-generated method stub
fillArray(array, null);
this.top = 0;
this.size = 0;
this.capacity = this.DEFAULT_SIZE;
this.array = new Object[this.capacity];
}
}
package test; public interface IStack<T> {
// 元素出栈,并返回出栈元素
public T pop(); // 元素入栈
public void push(T element); // 获取栈顶元素
public T peek(); // 判断栈是否为空
public boolean isEmpty(); // 清栈
public void clear();
}
输出结果如下:
此时栈是否为空:false
获取栈顶元素: 1
当前栈内元素共有: 6个
元素: 1出栈
当前栈内元素共有: 5个
当前栈内元素共有: 0个