版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_40301026/article/details/87886875
栈又称堆栈,是运行受限的线性表。
它只允许在其一端操作。
进行操作的一端被称为栈顶(top),另一端被称为栈底(bottom)。
其特征为新进的后出,后进先出。
根据数组操作的特性,选择数组下标大的一段,即线性表顺序存储的表尾来作为栈顶,此时入栈、出栈等操作可以在O(1)时间完成。
由于堆栈的操作都在栈顶完成,因此在顺序栈的实现中需要附设一个指针top来动态的指示栈顶元素在数组中的元素。
通常top可以用栈顶元素所在数组下标来表示,top=-1表示空栈。
package 栈的实现;
/**
* 栈接口,定义了栈的主要操作
* @author Administrator
*
* @param <E>
*/
public interface Stack<E> {
//返回堆栈的大小
public int getSize();
//判断堆栈是否为空
public boolean isEmpty();
//数据元素e入栈
public void push(E e);
//栈顶元素出栈
public E pop();
//取栈顶元素
public E peek();
//清空栈
public void empty();
}
package 栈的实现;
import java.util.Arrays;
public class ArrayStack<E> implements Stack{
private int top;//栈顶
private E[] datas;//栈
//初始化栈
public ArrayStack() {
this.datas = (E[])new Object[10];
this.top = -1;
}
public ArrayStack(int length){
if(length>0) {
this.datas = (E[])new Object[length];
this.top = -1;
} else {
throw new RuntimeException("大小不合法:"+length);
}
}
//栈扩容
private void addArraySize() {
int threshold = (int)(datas.length*0.75);//阀值
if(top+1>threshold) {
E newArray[] = (E[])new Object[datas.length<<1];
System.arraycopy(datas, 0,newArray, 0,top+1);
datas = newArray;
}
}
@Override
public int getSize() {
return top+1;
}
@Override
public boolean isEmpty() {
return top==-1;
}
public void push(Object e) {
top++;
addArraySize();//扩容检查
datas[top] = (E)e;
}
@Override
public E pop() {//扩容检查导致栈永远不会满
if(isEmpty()) {
System.out.print("栈为空!");
return null;
}
E result = datas[top];
datas[top] = null;
top--;
return result;
}
@Override
public E peek(){
if(isEmpty()) {
System.out.print("栈为空!");
return null;
}
E m = datas[top];
return m;
}
public void empty() {
Arrays.fill(datas, null);
top = -1;
}
}