合并两个排序的链表

    科技2025-10-11  15

    合并两个排序的链表

    输入两个递增排序的链表,合并这两个链表并使新链表中的结点仍然是按照递增排序的。

    样例 输入:1->3->5 , 2->4->5 输出:1->2->3->4->5->5

    无脑遍历

    时间复杂度O(n)

    class Solution { public ListNode merge(ListNode l1, ListNode l2) { if(l1 == null && l2 == null){ return null; } ListNode result = new ListNode(-1); ListNode temp = result; while(l1 != null && l2 != null){ if(l1.val > l2.val){ temp.next = l2; l2 = l2.next; }else{ temp.next = l1; l1 = l1.next; } temp = temp.next; } // l1或l2未遍历完 while(l1 != null){ temp.next = l1; l1 = l1.next; temp = temp.next; } while(l2 != null){ temp.next = l2; l2 = l2.next; temp = temp.next; } return result.next; } }
    Processed: 0.016, SQL: 8