在上一篇中用数组实现了“栈”,这次用链表实现。
代码如下:
1 public class LinkedStack<E> { 2 3 private int count;// 放入的个数 4 private Node head; // 头节点 5 6 /** 7 * 放入元素 8 * 9 * @param e 10 */ 11 public void push(E e) { 12 Node<E> node = new Node<>(e); 13 if (count == 0) { 14 this.head = node; 15 } else { 16 node.nextNode = this.head; 17 this.head = node; 18 } 19 count++; 20 } 21 22 /** 23 * 获取元素 24 * 25 * @return 26 */ 27 public E pop() { 28 if (count == 0) 29 throw new ArrayIndexOutOfBoundsException(); 30 Node<E> node = this.head; 31 this.head = this.head.nextNode; 32 count--; 33 return node.getT(); 34 } 35 36 private class Node<T> { 37 38 private T t; 39 private Node nextNode; 40 41 public Node(T t) { 42 this.t = t; 43 } 44 45 public T getT() { 46 return t; 47 } 48 49 public void setT(T t) { 50 this.t = t; 51 } 52 } 53 }