1.顺序栈
数组
尾插O(1),尾删O(1)
头插O(n),头删O(n)
1.1代码实现
import java.util.Arrays;
import java.util.EmptyStackException;
public class ArrayStack<T> {
private Object[] element; //元素
private int top; //有效个数
private static final int INITSIZE = 10;
public ArrayStack(){
element = new Object[INITSIZE];
}
//入栈
public void push(T value){
if(top == element.length){
element = Arrays.copyOf(element,element.length*2);
}
element[top++] = value;
}
//出栈
public void pop(){
if(top == 0){
return;
}
element[top-1] = null;
top--;
}
//获取栈顶元素
public Object peek(){
if(top == 0){
throw new EmptyStackException();
}
return element[top-1];
}
}
2.链式栈
尾插(tail):O(1),尾删O(n)
头插:O(1),头删O(1)
2.1 代码实现
public class LinkStack <E extends Comparable<E>>{
private SingleLink<E> link;
public LinkStack(){
this.link = new SingleLink<>();
}
public void push(E value){
link.addHead(value);
}
public void pop(){
link.removeHead();
}
public E peek(){
return link.getHead().getValue();
}
}
今天也要好好学习呀~