水下功夫做透,水上才能顺风顺水。

两个有序列表合并(空间复杂度O1)

 public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
        // 使用带头结点的链表解决问题
        // 待输出链表的头部
        ListNode head = new ListNode();

        // 待输出链表的 cur 结点
        ListNode cur = head;
        while(list1 != null && list2 != null) {
            if(list1.val > list2.val) {
                cur.next = list2;
                list2 = list2.next;
            }else{
                cur.next = list1;
                list1 = list1.next;
            }
            cur = cur.next;
        }

        if(list1 != null) cur.next = list1;
        if(list2 != null) cur.next = list2;

        return head.next;

    }

 

posted @ 2022-03-03 15:53  北方寒士  阅读(76)  评论(0)    收藏  举报