头结点一般称为head。其数据域不存储数据,指针域指向第一个数据域有内容的结点(一般把该结点称为第一个结点)。
/**
* @author admin
* @version 1.0.0
* @ClassName LoopNode.java
* @Description TODO
* @createTime 2021年08月15日 09:31:00
*/
public class NodeTest {
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).append(new Node(4));
node1.show();
node2.show();
node2.insert(new Node(5));
node1.show();
//System.out.println(node1.next);//返回的是地址值Node@1b6d3586
// System.out.println(node1.getNext());//返回的是地址值Node@1b6d3586
//System.out.println(node1.next.data);//返回的是结点1的下一个结点存储的数据
//System.out.println(node1.next.next.data);//返回1 2 3 4
}
}
public class Node {
int data;//存储的数据
Node next;
//构造器,创对象时同时赋值
Node(int num){
this.data=num;
}
//添加结点
public Node append(Node node){
Node currentnode =this;
while (true){
Node nextNode =currentnode.next;
if (nextNode==null)//currentnode后面再无结点,即currentnode是最后一个结点。
break;
currentnode=nextNode;
}
currentnode.next=node;
return this;//返回添加的结点。
}
//返回该结点下一个结点
public Node getNext(){
return this.next;
}
//返回该结点存储的数据。
public int getData(){
return this.data;
}
//展示结点
public void show(){
Node currentnode=this;
while (true){
System.out.print(currentnode.data+" ");
currentnode=currentnode.next;
if(currentnode==null)
break;
}
System.out.println();
}
//删除结点
public void removenext(){
Node newnext=next.next;
this.next=newnext;
}
//插入结点
public void insert (Node node){
Node nextnext=this.next;
this.next=node;
node.next=nextnext;
}
}