合并有序链表思路

  public ListNode Merge (ListNode pHead1, ListNode pHead2) {
        if (pHead1 == null) {
            return pHead2;
        }
        if (pHead2 == null) {
            return pHead1;
        }
        ListNode cur1 = pHead1;
        ListNode cur2 = pHead2;
        ListNode pre2 = new ListNode(-1);
        pre2 .next = cur2;
        while (cur2 != null && cur1 != null) {
            if (cur2.val < cur1.val) {
                //
                ListNode temp = cur1.next;
                //插入之前判断

                if(cur2.next !=null && cur2.next.val < cur1.val){
                    cur2 = cur2.next;
                    pre2 = pre2 .next;
                    continue;
                }
                cur1.next = cur2.next;
                cur2.next = cur1;
                cur2 = cur1.next;
                pre2 = cur1;
                cur1 = temp;
            } else { //cur2>=cur1

                ListNode temp = cur1.next;
                //插入cur1之前判断后面值,是否小于,当前cur1, 小于就比较cur的下一个
                if(cur2.next != null && cur2.next.val < cur1.val){
                    cur2 = cur2.next;
                    pre2 = pre2 .next;
                    continue;
                }
                pre2 .next = cur1;
                cur1.next = cur2;
                cur1 = temp;
                pre2 = pre2 .next;
                //cur2保持不变
            }//两者相同值应该额外判断,同步后移

        }//这此循环走完,好像只能剩一条链了,链1会断掉
        //把可能断掉的链补全
        if(cur1 != null){
            pre2 .next = cur1;
        }
        return pHead1.val > pHead2.val ? pHead2 : pHead1;
    }

错误点:
1 pre的更新。是pre的更新,不是pre.next的更新。
2 插入地方的判断,不能值判断当前值,还要判断cur2的后续值。要不然会出现26,27,26,26的情况。
3 链的断裂连接,我以为不会有断链情况,但cur2用完,cur1有剩余的时候会断链。
优秀代码
递归实现

   def Merge(self, pHead1, pHead2):
        # write code here
        if not pHead1:
            return pHead2
        if not pHead2:
            return pHead1
         
        result = ListNode(-1)
        cur = result
        while pHead1 and pHead2:
            # 元素对比
            if pHead1.val <= pHead2.val:
                cur.next = pHead1
                pHead1 = pHead1.next
            else:
                cur.next = pHead2
                pHead2 = pHead2.next
            # 指针右移动一位
            cur = cur.next
        # 拼接未对比的链表
        cur.next = pHead1 if pHead1 else pHead2
        return result.next

总结
只比较两个值就行,当前指针指向较小的结点,较小的结点向后移。进入下一轮比较。
想复杂了

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值