3、循环链表
public class LoopNode {
//节点内容
int data;
//下一个结点
LoopNode next = this; //自己循环自己
public LoopNode(int data) {
this.data = data;
}
//删除节点
public void removeNext() {
//取出下下个节点
LoopNode newNext = next.next;
//把下下个节点设置为当前节点的下个节点
this.next = newNext;
}
//插入节点
public void after(LoopNode node) {
//取出下一个节点作为下下个节点
LoopNode nextNext =next;
//把新节点作为当前节点的下个节点
this.next = node;
//把下下个节点设置为新节点的下个节点
node.next = nextNext;
}
//获取下一个节点
public LoopNode next() {
return this.next;
}
//获取节点中的数据
public int getData() {
return this.data;
}
}
主函数
public class TestLoopNode {
public static void main(String[] args) {
LoopNode n1 = new LoopNode(1);
LoopNode n2 = new LoopNode(2);
LoopNode n3 = new LoopNode(3);
LoopNode n4 = new LoopNode(4); //每一个都是单独的循环节点
//增加节点
n1.after(n2);
n2.after(n3);
n3.after(n4);
System.out.println(n1.next().getData());
System.out.println(n2.next().getData());
System.out.println(n3.next().getData());
System.out.println(n4.next().getData()); //1后面是2,2后面是3,3后面是4,是后面是1
}
}
4、双链表
public class DoubleNode {
//上一个节点
DoubleNode pre = this;
//下一个节点
DoubleNode next = this;
//节点数据
int data;
public DoubleNode(int data) {
this.data=data;
}
//增加节点
public void after(DoubleNode node) {
//取出下个节点作为下下个节点
DoubleNode nextNext = next;
//把新节点当做当前节点的下个节点
this.next = node;
//当前节点作为新节点的前一个节点
node.pre = this;
//下下个节点作为新节点的下个节点
node.next = nextNext;
//让下下个节点的上一个节点为新节点
nextNext.pre = node;
}
//下个节点
public DoubleNode next() {
return this.next;
}
//上一个节点
public DoubleNode pre() {
return this.pre;
}
}