Java 简单链表实现小🌰

[java]
/**
* @Description: 链表实现
* @Author: Jasonote
* @Date: 2017/11/28
**/
public class linkedList {
public static void main(String args[]) {
Link link = new Link();
link.add("hello");
link.add("world");
link.print();//展示数据
//准备数据
// Node root = new Node("根节点");
// Node n1 = new Node("A");
// Node n2 = new Node("B");
// root.setNext(n1);
// n1.setNext(n2);
// print(root);
//取出数据
}

public static void print(Node current) {
//递归结束条件
if (current == null) {
return;
}
System.out.println(current.getData());
print(current.getNext());
}
}

class Node {
//保存的数据
private String data;
//要保存的下一个节点
private Node next;

public Node(String data) {
this.data = data;
}

public void setNext(Node next) {
this.next = next;
}

public Node getNext() {
return this.next;
}

public String getData() {
return this.data;
}

//实现节点添加
public void addNode(Node newNode) {
if (this.next == null) {
this.next = newNode;
} else {
this.next.addNode(newNode);
}
}

public void printNode() {
System.out.println(this.data);
if (this.next != null) {
this.next.printNode();
}
}
}

class Link {
private Node root;

public void add(String data) {
Node newNode = new Node(data);
if (this.root == null) {
this.root = newNode;
} else {
this.root.addNode(newNode);
}

}

public void print() {//输出数据
if (this.root != null) {
this.root.printNode();
}
}
}
[/java]

Jason.wang

When you find your talent can't afford to be ambitious, be quiet and study !

You may also like...