- 首先实现一个节点类:
package jimo.love;
public 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 data;
}
public void setData(String data) {
this.data = data;
}
}
- 然后在主方法中生成节点,完成连接关系,并打印出来,看代码有解释:
public class Test {
public static void main(String[] args) {
//1.准备所有数据
Node head = new Node("头节点");
Node n1 = new Node("n1");
Node n2 = new Node("n2");
head.setNext(n1);
n1.setNext(n2);
//2.取出所有数据
//方法一:
Node curNode = head;
while(curNode!=null){
System.out.println(curNode.getData());
curNode = curNode.getNext();
}
//方法二,递归方式:
print(head);
}
//采用递归方式
public static void print(Node curNode){
if(curNode==null){
return ;
}
System.out.println(curNode.getData());
print(curNode.getNext());
}
}
转自java自定义链表