class Link {
private class Node {
private Node next;//下一个节点
private String data;//保存数据
public Node(String data) {//保存数据构造方法
this.data = data;
}
//添加新节点
public void addNode(Node newNode) {
if (this.next == null) {//如果此节点为null
this.next = newNode;//新节点为此节点
} else {//如果此节点不为null,递归调用。
this.next.addNode(newNode);
}
}
//输出数据
public void printNode() {
System.out.println(this.data);//输出现在节点的内容
if (this.next != null) {//如果下一个节点不为null
this.next.printNode();//输出下一个节点的数据
}
}
}
//==================以上为内部类==========================
private Node root;//设置根节点
//添加数据方法
public void add(String data) {
Node newNode = new Node(data);//先将数据放入一个节点中
if (this.root == null) {//如果根节点为空
this.root = newNode;//此newNode节点为根节点
} else {
this.root.addNode(newNode);//如果根节点存在,递归调用,把newNode设置为root的下一个节点
}
}
//输出数据的方法
public void print() {
if (this.root != null) {//现在存在根节点
root.printNode();//交给Node类输出
}
}
}
public class NodeTest {
public static void main(String[] args) throws Exception {
Link link = new Link();
link.add("大家好!");
link.add("我是渣渣辉");
link.add("欢迎来到贪玩揽月!");
link.print();
}
}