1.栈基础
结构特性:先进后出
2.手写基于动态链表的栈
package com.tc.javabase.datastructure.array.stack;
import com.tc.javabase.datastructure.array.ArrayList;
import com.tc.javabase.datastructure.stack.Stack;
/**
* 基于动态数组实现的栈
*
* * 结构特性:先进后出
* *
* * 时间复杂度分析:
* * 入栈: O(1)
* * 出栈: O(1)
* * 查询栈顶元素: O(1)
* *
* * 综上所述: 基于动态数组的操作时间复杂度都是O(1)
* @param <E>
*/
public class ArrayStack<E> implements Stack<E> {
private ArrayList<E> arrayList;
public ArrayStack(int capacity){
arrayList = new ArrayList<>(capacity);
}
public ArrayStack(){
arrayList = new ArrayList<>();
}
@Override
public int getSize(){
return arrayList.getSize();
}
@Override
public boolean isEmpty(){
return arrayList.isEmpty();
}
public int getCapacity(){
return arrayList.getCapacity();
}
@Override
public void push(E e){
arrayList.addLast(e);
}
@Override
public E pop(){
return arrayList.removeLast();
}
@Override
public E peek(){
return arrayList.getLast();
}
@Override
public String toString(){
StringBuilder res = new StringBuilder();
res.append("Stack: ");
res.append('[');
for(int i = 0; i < arrayList.getSize() ; i ++){
res.append(arrayList.get(i));
if(i != arrayList.getSize() - 1)
res.append(", ");
}
res.append("] top");
return res.toString();
}
}