class Node {//该节点省略data域
public int no;
public Node next;
public Node pre;
public Node(int no) {
if (no >= 0) {//要求no要大于0
this.no = no;
}
}
@Override
public String toString() {
return "Node{" +
"no=" + no +
'}';
}
}
public class DoubleLinkedList {
Node head = new Node(0);
public void add(Node node) {//节点加入链表尾
Node temp = head;
while (true) {
if (temp.no == node.no) {//该编号节点已存在
return;
} else if (temp.next == null) {
break;
}
temp = temp.next;
}
temp.next = node;
node.pre = temp;
}
public void addByOrder(Node node) {//根据节点编号升序加入
Node temp = head;
while (true) {
if (temp.no == node.no) {//该编号节点已存在
return;
} else if (temp.next == null) {//加入链尾
break;
} else if (temp.next.no > node.no) {//插入第一个编号比node大节点的前一位
temp.next.pre = node;
node.next = temp.next;
break;
}
temp = temp.next;
}
temp.next = node;
node.pre = temp;
}
public void update(Node node) {//更新节点
Node temp = head.next;
while (true) {
if (temp == null) {//该编号节点不存在
return;
} else if (temp.no == node.no) {//找到该编号节点
if (temp.next != null) {
temp.next.pre = node;
node.next = temp.next;
}
temp.pre.next = node;
node.pre = temp.pre;
return;
}
temp = temp.next;
}
}
public void delete(int no) {
Node temp = head.next;
while (true) {
if (temp == null) {//该编号节点不存在
return;
}
if (temp.no == no) {//被跳过的节点没有引用,被回收
temp.pre.next = temp.next;
if (temp.next != null) {//防止要删除的节点在链尾
temp.next.pre = temp.pre;
}
return;
}
temp = temp.next;
}
}
public void show() {//打印链表
Node temp = head.next;
while (true) {
if (temp == null) {
return;
}
System.out.println(temp);
temp = temp.next;
}
}
public int getLength() {//获取链表有效节点个数
int length = 0;
Node temp = head.next;
while (temp != null) {
length++;
temp = temp.next;
}
return length;
}
//用一条空的单向链表调用,传入两条待合并单向链表各自的第一个有效节点
public void merge(Node n1, Node n2) {
Node cur = head;
while (n1 != null && n2 != null) {
if (n1.no <= n2.no) {
cur.next = n1;
n1.pre = cur;
n1 = n1.next;
} else {//n1.no > n2.no
cur.next = n2;
n2.pre = cur;
n2 = n2.next;
}
cur = cur.next;
}
//若n1全部比较合并后,n2剩余节点加入链尾;反之亦然
if (n1 == null) {
cur.next = n2;
n2.pre = cur;
} else {
cur.next = n1;
n1.pre = cur;
}
}
}