简介
单向链表是通过节点类实现的,每个节点包含两个成员变量,一个是存储的信息,一个是下一个节点的引用(地址值)。
因此通过当前节点,我们就可以获取下一个节点,以此类推就可以火球整个链表的值。
Node类
package com.wuxudong.LinkedList;
//定义节点
public class Node {
//每个节点存储了都存储了两个部分,一个是该节点的数据,还有下一个节点的地址值
//数据
private int data;
//下一个节点
private Node next;
public Node(int data){
this.data=data;
}
//获取下个节点的方法
public Node next(){
return this.next;
}
//定义获取数据的方法
public int getData(){
return this.data;
}
//定义方法追加节点
public Node append(Node node){
//获取当前的节点
Node currentNode=this;
while (true){
//获取当前节点的下个节点
Node nextNode=currentNode.next;
if(nextNode==null){
//当前节点为最后一个节点
break;
}
currentNode=nextNode;
}
return currentNode.next=node;
}
//删除下一个节点
public void removeNext(){
this.next=next.next();
}
//显示所有节点的信息
public void show(){
//获取当前的节点
Node currentNode=this;
while (true){
//打印当前节点的数值
System.out.print(currentNode.getData()+" ");
currentNode=currentNode.next();
if(currentNode==null){
break;
}
}
System.out.println();
}
//插入节点
public void insertNode(Node node){
//获取当前的节点
Node currentNode=this;
//将保存节点的下一个节点
Node nextNode=currentNode.next();
//将当前节点的下一个节点指向新节点
currentNode.next=node;
//将新节点的下一个节点指当前节点的下一个节点
node.next=nextNode;
}
}
测试类
package com.wuxudong.LinkedList;
public class MyLinkedListTest {
public static void main(String[] args) {
Node node1=new Node(1);
Node node2=new Node(2);
Node node3=new Node(3);
//追加节点
node1.append(node2).append(node3);
node1.show();
node2.insertNode(new Node(4));
node1.show();
}
}