链表的基本介绍
如果现在要保存多个对象,那么首先可以想到的就是对象数组;如果我们想要保存多个任意对象,那么可以想到的一定是Object型的数组。
Object[] data=new Object[4];
但是数组最大的缺点就是长度固定,在实际开发中我们并不知道自己到底要用多少个对象,所以如果我们使用对像数组申请的空间多或者少都有可能造成空间浪费。这个时候,我们就想定义一个动态申请空间有多少数据就存多少数据的结构——链表。
范例:Java链表结点结构
class Node{
private Object data;//保存节点中的数据
private Node next;//引用,指向下一个结点
//构造函数
public Node(Object data){
this.data=data;
}
//得到对象数据
public Object getData(){
return this.data;
}
//得到对象的下一个结点
public Node getNext(){
return this.next;
}
//设置对象的下一个结点
public void setNext(Node next){
this.next=next;
}
//设置对象的数据
public void setData(Object data){
this.data=data;
}
}
public class Test {
public static void main(String[] args){
//封装结点
Node head=new Node("头结点");
Node first=new Node("结点1");
Node second=new Node("结点2");
Node last=new Node("尾结点");
//结点挂载
head.setNext(first);
first.setNext(second);
second.setNext(last);
//打印结点
print(head);
}
public static void print(Node node){
Node cur=node;
while(cur!=null){
System.out.println(node.getData());
node=node.getNext();
}
}
}
观察上面链表的实现&#