链式栈即底层通过链表实现的栈,本文所用到的链表是之前实现单链表
https://www.jianshu.com/p/9988a5df88ca
时间复杂度
入栈:O(1)
出栈:O(1)
接口类:
public interface Stack<E> {
int getSize();
boolean isEmpty();
void push(E e);
E pop();
E peek();
}
实现类:
public class LinkedListStack<E> implements Stack<E> {
LinkedList<E> list = new LinkedListImpl<>();
@Override
public int getSize() {
return list.size();
}
@Override
public boolean isEmpty() {
return list.isEmpty();
}
@Override
public void push(E e) {
list.addFirst(e);
}
@Override
public E pop() {
return list.removeFirst();
}
@Override
public E peek() {
return list.get(0);
}
@Override
public String toString() {
StringBuilder res = new StringBuilder("top ");
res.append(list);
return res.toString();
}
}
测试:
public class Main {
public static void main(String[] args) {
Stack<Integer> stack = new LinkedListStack<>();
for (int i = 0 ; i < 10 ; i++){
stack.push(i);
System.out.println(stack);
}
for (int i = 0; i < 10 ; i++){
stack.pop();
System.out.println(stack);
}
}
}