算法:把两个有序链表合并成一个新的有序链表

72 阅读1分钟
/**
 * 合并两个有序链表 ,返回一个新的有序链表
 * @param head1
 * @param head2
 * @return
 */
public static ListNode doubleSortedLinkedListMerge(ListNode head1, ListNode head2) {
    // 如果任意一个链表为空,直接返回另外一个非空链表节点
    if (head1 == null || head2 == null) {
        return head1 == null ? head2 : head1;
    }

    // 先找到头节点
    ListNode head = head1.value <= head2.value ? head1 : head2;
    // 准备一个滑动指针
    ListNode prev = head;
    ListNode first = head.next;
    ListNode second = head == head1 ? head2 : head1;
    
    while (first != null && second != null) {
        if (first.value <= second.value) {
            prev.next = first;
            first = first.next;
        } else {
            prev.next = second;
            second = second.next;
        }
        prev = prev.next;
    }

    prev.next = first != null ? first : second;
    return head;
}
```
```