栈是一种后进先出的数据结构(Last In First Out)
Undo操作(撤销)
系统栈:存储我们调用的程序
我在这里写的Stack是用数组实现的
package www.zxx;
public interface Stack<E> {
int getSize();
boolean isEmpty();
void push(E e);
E pop();
E top();
}
package www.zxx;
public class ArrayStack<E> implements Stack<E> {
Array<E> array;
public ArrayStack(int capacity) {
array = new Array<>(capacity);
}
public ArrayStack() {
array = new Array<>();
}
@Override
public int getSize() {
// TODO Auto-generated method stub
return array.getSize();
}
@Override
public boolean isEmpty() {
// TODO Auto-generated method stub
return array.isEmpty();
}
@Override
public void push(E e) {
// TODO Auto-generated method stub
array.addLast(e);
}
@Override
public E pop() {
// TODO Auto-generated method stub
return array.removeLast();
}
@Override
public E top() {
// TODO Auto-generated method stub
return array.getLast();
}
public int getCapcity() {
return array.getCapacity();
}
@Override
public String toString() {
StringBuilder res = new StringBuilder();
res.append("Stack:[");
for(int i = 0 ; i <array.getSize() ;i++) {
res.append(array.get(i));
if(i!=array.getSize()-1)
res.append(',');
else
res.append("] top");
}
return res.toString();
}
public static void main(String[] args) {
ArrayStack<Integer> stack = new ArrayStack<>();
for(int i = 0 ; i < 5 ; i++) {
stack.push(i);
System.out.println(stack);
}
stack.pop();
System.out.println(stack);
}
}
对于我们实现的接口中操作的时间复杂度都是O(1),就算是触发了resize在均摊以后也是O(1)