本章目标
了解引用传递的深入应用
了解链表的基本概念
链表
链表是在数据结构中经常见到的一种形式,实际上在java中也可以通过引用传递的方式进行实现,本节为读者简单介绍一下Java中实现链表的基本形式。
在讲解链表之前,首先为读者简单介绍一下链表的基本概念。所谓的链表就好象火车车厢那样,从火车头开始,每一节车厢之后都连着后一节车厢
节点类设计
每一节车厢就相当于是一个节点每一个节点除了要保存自己的内容之外,还要保存下一个节点的引用,那么这样的节点该如何通过程序表示呢?
节点类
class Node {
private String data; // 保存节点内容
private Node next; // 保存下一个节点
public Node(String data) { // 构造方法设置节点内容
this.data = data;
}
public String getData() { // 得到节点内容
return this.data;
}
public void setNext(Node next) { // 设置下一个节点
this.next = next;
}
public Node getNext() { // 取得下一个节点
return this.next;
}
};
设置节点
public class LinkDemo01 {
public static void main(String args[]) {
Node root = new Node("火车头"); // 定义根节点
Node n1 = new Node("车厢-A"); // 定义第一个车厢
Node n2 = new Node("车厢-B"); // 定义第二个车厢
Node n3 = new Node("车厢-C"); // 定义第三个车厢
root.setNext(n1); // 火车头的下一个节点是第一个车厢
n1.setNext(n2); // 第一个车厢的下一个节点是第二个车厢
n2.setNext(n3); // 第二个车厢的下一个节点是第三个车厢
}
}
链表输出
public class LinkDemo01 {
public static void main(String args[]) {
Node root = new Node("火车头"); // 定义根节点
Node n1 = new Node("车厢-A"); // 定义第一个车厢
Node n2 = new Node("车厢-B"); // 定义第二个车厢
Node n3 = new Node("车厢-C"); // 定义第三个车厢
root.setNext(n1); // 火车头的下一个节点是第一个车厢
n1.setNext(n2); // 第一个车厢的下一个节点是第二个车厢
n2.setNext(n3); // 第二个车厢的下一个节点是第三个车厢
}
}
链表输出
public class LinkDemo01 {
public static void main(String args[]) {
Node root = new Node("火车头"); // 定义根节点
Node n1 = new Node("车厢-A"); // 定义第一个车厢
Node n2 = new Node("车厢-B"); // 定义第二个车厢
Node n3 = new Node("车厢-C"); // 定义第三个车厢
root.setNext(n1); // 火车头的下一个节点是第一个车厢
n1.setNext(n2); // 第一个车厢的下一个节点是第二个车厢
n2.setNext(n3); // 第二个车厢的下一个节点是第三个车厢
printNode(root) ; // 从根节点输出
}
public static void printNode(Node node){
System.out.print(node.getData()+"\t") ; // 输出数据
if(node.getNext()!=null){ // 判断节点是否为空
printNode(node.getNext()) ; // 还要继续向下打印
}
}
}
class Node{
private String data;//保存节点内容
private Node next;//保存下一个节点
public Node(String data){//构造方法设置节点内容
this.data = data;
}
public String getData() {//得到节点的内容
return data;
}
public Node getNext() {//设置下一个节点
return next;
}
public void setNext(Node next) {//取得下一个节点
this.next = next;
}
}
public class LinkDemo01 {
public static void main(String[] args){
Node root = new Node("火车头");//定义根节点
Node n1 = new Node("车厢 - A");//定义第 1 个车厢
Node n2 = new Node("车厢 - B");//定义第 2 个车厢
Node n3 = new Node("车厢 - C");//定义第 3 个车厢
root.setNext(n1);//头车头的下一个节点是第 1 个车厢
n1.setNext(n2);//第 1 个车厢的下一个节点是第 2 个车厢
n2.setNext(n3);//第 2 个车厢的下一个节点是第 3 个车厢
printNode(root);//从根节点输出
}
public static void printNode(Node node){
System.out.print(node.getData()+"、");//输出数据
if(node.getNext() != null){//判断节点是否为空
printNode(node.getNext());//继续向下打印
}
}
/*结果:
* 火车头、车厢 - A、车厢 - B、车厢 - C、
* */
}