可以把链表头作为栈顶,用链表作为栈的底层实现( LinkedListStack<E> implements Stack<E>),来实现出栈这样一个结构。
1 public class LinkedListStack<E> implements Stack<E> { 2 3 private LinkedList<E> list; 4 5 public LinkedListStack(){ 6 list = new LinkedList<>(); 7 } 8 9 @Override 10 public int getSize(){ 11 return list.getSize(); 12 } 13 14 @Override 15 public boolean isEmpty(){ 16 return list.isEmpty(); 17 } 18 19 @Override 20 public void push(E e){ 21 list.addFirst(e); 22 } 23 24 @Override 25 public E pop(){ 26 return list.removeFirst(); 27 } 28 29 @Override 30 public E peek(){ 31 return list.getFirst(); 32 } 33 34 @Override 35 public String toString(){ 36 StringBuilder res = new StringBuilder(); 37 res.append("Stack: top "); 38 res.append(list); 39 return res.toString(); 40 } 41 42 public static void main(String[] args) { 43 44 LinkedListStack<Integer> stack = new LinkedListStack<>(); 45 46 for(int i = 0 ; i < 5 ; i ++){ 47 stack.push(i); 48 System.out.println(stack); 49 } 50 51 stack.pop(); 52 System.out.println(stack); 53 } 54 }