使用只有头结点的链表实现栈

使用静态内部类充当单链表 


1
package db; 2 3 /** 4 * 只有头结点实现栈 5 * 6 * @author fightzhao 7 * 8 */ 9 public class Stack<E> { 10 /* 11 * 有以下方法 入栈 push(E x) 出栈pop() 栈顶元素top() 12 */ 13 private static class Node<E> { 14 public Node<E> next; 15 public E data; 16 17 public Node(E data, Node<E> next) { 18 this.data = data; 19 this.next = next; 20 } 21 } 22 23 private Node<E> head; 24 private int theSize; 25 26 public Stack() { 27 head = null; 28 } 29 30 public int size() { 31 return theSize; 32 } 33 34 public void push(E data) { 35 Node<E> pNode = new Node<E>(data, head); 36 head = pNode; 37 theSize++; 38 } 39 40 public void pop() { 41 head = head.next; 42 theSize--; 43 } 44 45 public E top() { 46 return head.data; 47 } 48 49 public void printAll() { 50 Node<E> pNode = head; 51 while (pNode != null) { 52 System.out.println(pNode.data); 53 pNode = pNode.next; 54 } 55 56 } 57 }

 

posted @ 2016-03-04 19:48  fightzhao  阅读(395)  评论(0编辑  收藏  举报