/**
* 书本:《Thinking In Java》
* 功能:用java实现堆栈功能
* 文件:LinkedStack.java
* 时间:2015年4月17日14:23:34
* 作者:cutter_point
*/
package Lesson15_generices;
public class LinkedStack<T>
{
private static class Node<U>
{
U item;
Node<U> next; //下一个对象的引用
Node() { item = null; next = null; } //默认构造函数的都是空的
Node(U item, Node<U> next)
{
this.item = item;
this.next = next;
}
boolean end() { return item == null && next == null; }
}
private Node<T> top = new Node<T>(); //栈顶元素
public void push(T item)
{
top = new Node<T>(item, top); //把这个新的元素赋值给栈顶引用
}
public T pop()
{
T result = top.item; //把栈顶的元素弹出去
if(!top.end())
top = top.next;
return result;
}
public static void main(String[] args)
{
LinkedStack<String> lss = new LinkedStack<String>(); //创建一个堆栈类
for(String s : "My name is cutter_point!".split(" "))
{
lss.push(s);
}
String s;
while((s=lss.pop()) != null)
System.out.println(s);
}
}
输出:
cutter_point!
is
name
My