public class LinkedStack<T> {
//内部的节点类,它 包含两个区域
//item存放 内容,next存放下前一个节点的指针
private 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 : "Phasers on stun!".split(" ")){
lss.push(s);
}
String s ;
while((s = lss.pop()) != null){
System.out.println(s);
}
}
}
备注来之:thinking in java 4th
本文介绍了一个使用Java实现的链表栈数据结构。通过定义一个内部的节点类,该类包含内容和指向下一个节点的指针,实现了链表栈的基本操作,如push和pop。示例代码展示了如何创建链表栈并进行逆序字符串的操作。
3859

被折叠的 条评论
为什么被折叠?



