ArrayList来实现一个栈或者使用LikedList当做栈来使用
ArrayList来实现一个栈:
import java.util.ArrayList; public class MyStack<T> implements Stack<T>{ ArrayList a = new ArrayList<>(); @Override public boolean isEmpty() { // TODO Auto-generated method stub return a.isEmpty(); } @Override public T peek() { // TODO Auto-generated method stub return (T)a.get(0); } @Override public T pop() { // TODO Auto-generated method stub return (T)a.remove(0); } @Override public void push(T element) { // TODO Auto-generated method stub a.add(0, element); } @Override public int size() { // TODO Auto-generated method stub return a.size(); } @Override public void clear() { // TODO Auto-generated method stub a.clear(); } }
测试:
public static void main(String[] args) { MyStack<String> stack = new MyStack<>(); System.out.println("是否为空" + stack.isEmpty()); stack.push("1"); stack.push("2"); System.out.println("是否为空" + stack.isEmpty()); System.out.println(stack.pop()); System.out.println(stack.peek()); System.out.println("当前元素个数" + stack.size()); stack.clear(); System.out.println("清空后 当前元素个数" + stack.size()); }
执行结果:
是否为空true 是否为空false 2 1 当前元素个数1 清空后 当前元素个数0
使用LikedList做栈来使用
LikedLista本身就实现了栈定义的所有方法,所有就可用之间将LikedList当作栈来使用
public static void main(String[] args) { LinkedList<String> stack = new LinkedList<>(); System.out.println("是否为空" + stack.isEmpty()); stack.push("1"); stack.push("2"); System.out.println("是否为空" + stack.isEmpty()); System.out.println(stack.pop()); System.out.println(stack.peek()); System.out.println("当前元素个数" + stack.size()); stack.clear(); System.out.println("清空后 当前元素个数" + stack.size()); }
执行结果:
是否为空true 是否为空false 2 1 当前元素个数1 清空后 当前元素个数0