/**
* 将两条有序链表合并为一条链表
*
* @param list1
* @return 以两条链表中最小的有效数据作为循环,创建两个指针域,作为遍历和合并的操作节点。比较两个节点之间的大小,小的先放大的后放。操作完成后,一定某一条链表上还有数据,然后将该链表的数据在最终的合并链表尾部追加即可
*/
public Node merge(Node head1, Node head2) {
if (head1 == null && head2 == null) {
return null;
}
// head1与head2任一为null,则无需合并,直接返回另一个即可
if (head1 == null) {
return head2;
}
if (head2 == null) {
return head1;
}
Node headNode = null;
Node last = null;
if (head1.no < head2.no) {
headNode = head1;
last = head1;
head1 = head1.next;
} else {
headNode = head2;
last = head2;
head2 = head2.next;
}
// 如果head1的值小于head2的值,则新链表的尾节点的next为head1,并且head1指向其next
// 否则为head2,并且head2指向其next
while (head1 != null && head2 != null) {
if (head1.no < head2.no) {
last.next = head1;
last = head1;
head1 = head1.next;
} else {
last.next = head2;
last = head2;
head2 = head2.next;
}
}
if (head1 != null) {
last.next = head1;// 如果head1链表不为null,则直接放到合并链表的尾部
} else {
last.next = head2;// 如果head2链表不为null,则直接放到合并链表的尾部
}
// 因为合并链表的头节点是随意初始化的,所以真正合并后的链表头节点应该是当前头节点的next
return headNode.next;
}