2.14 双向循环链表
双链表
增加节点的实现原理
代码实现:
DoubleNode类
package com.kami.leetcode.linked;
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;
}
//获取数据
public int getData(){
return this.data;
}
}
测试类TestDoubleNode
package com.kami.leetcode.linked;
public class TestDoubleNode {
public static void main(String[] args) {
//创建节点
DoubleNode d1 = new DoubleNode(1);
DoubleNode d2 = new DoubleNode(2);
DoubleNode d3 = new DoubleNode(3);
//追加节点
d1.after(d2);
d2.after(d3);
//查看上一个, 自己,下一个节点的内容
System.out.println(d2.pre().getData());
System.out.println(d2.getData());
System.out.println(d2.next().getData());
System.out.println(d3.next().getData());
System.out.println(d1.pre().getData());
}
}
结果: