LeetCode:Merge Two Sorted Lists

Merge Two Sorted Lists


1、题目:
Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.


2、代码:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
        ListNode *cur1=l1,*pre1=l1,*cur2=l2,*pre2=l2,*h2=l2;
        while(cur1&&cur2)
        {
            //寻找插入点
            while(cur1&&cur1->val<cur2->val)
            {
                pre1=cur1;
                cur1=cur1->next;
            }
            while(cur1&&cur2&&cur1->val>=cur2->val)
            {
                pre2=cur2;
                cur2=cur2->next;
            }
            if(cur1==pre1&&cur2!=pre2)//两种特殊情况
            {
                l1=l2;
                pre2->next=cur1;
                pre2=cur2;//更新pre2
            }
            else if(cur1!=pre1&&cur2==pre2)
            {
                l2=l1;
                pre1->next=h2;
                cur2=cur2->next;
            }
            else
            {
                pre2->next=cur1;
                pre1->next=h2;
                pre2=cur2;
            }
            h2=cur2;//更新h2
        }
        if(cur1)
        {
            return l1;
        }
        else
        {
            return l2;
        }
    }
};

3、总结:
我写了一下午啊 ,对着leetcode,肉眼寻找错误的感觉真是太难熬了,我都投降了,打开IDE,一切准备就绪的时候,突然发现了问题所在。写一下这个程序要注意的问题。
A、头结点更新,注意返回的是结果链表。
B、链表链接好后,要更新pre指针,不然循环开始或再次链接会更改pre。
C、两种特殊情况排除。
D、pre和next的前进步伐一致。


2016.7.11更新


http://www.cnblogs.com/zsboy/p/3887229.html
阅读有感

//别人家的代码。归并排序的合并部分
        ListNode *helper=new ListNode(0);
        ListNode *head=helper;
        while(l1 && l2)
        {
             if(l1->val<l2->val) 
             {
                 helper->next=l1;
                 l1=l1->next;
             }
             else 
             {
                 helper->next=l2;
                 l2=l2->next;
             }
             helper=helper->next;
        }
        if(l1) 
        {
            helper->next=l1;
        }
        if(l2) 
        {
            helper->next=l2;
        }
        return head->next;

总结:
这段代码很好懂,看来算法要学好。
A、辅助链表建立,有头节点就好了。
B、谁小就接谁,接了后前进。
C、将没有接完的链表接上。返回头结点后面的链表。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值