使用内部单向链表实现的一个简单堆栈。通过本代码可以对泛型,单向链表及堆栈的实现有较全面的了解。单向链表中的每一个元素(或称节点)中有一个next域指向该元素的下一个元素,这样就可以将多个元素一个个链接起来,形成一个单向链表。
/** * 单向列表实现的简单堆栈 */ package generics; /** * 泛型单向堆栈类 * @author LYL * */ public class LinkedStack<T> { /** * 堆栈中一个节点元素 * @author LYL * * @param <U> */ private class Node<U>{ private U item; private Node<U> next; public Node(){ this.item=null;this.next=null;} public Node(U item,Node<U> next){ this.item=item; this.next=next; } public boolean end(){ return item==null && next==null; } } //栈顶 private Node<T> top=new Node<T>(); /** * 入栈 * @param item */ public void push(T item){ top=new Node<T>(item,top); } /** * 出栈 * @return */ public T pop(){ //取出栈项元素 T result=top.item; if(!top.end()){ //如果非最后一个节点,则改变栈项 top=top.next; } return result; } public static void main(String[] args){ LinkedStack<String> stack=new LinkedStack<String>(); for(String s : "美国,中国".split(",")){ stack.push(s); } String s; while((s=stack.pop())!=null){ System.out.println(s); } } }