LeetCode:Merge Two Sorted Lists

来源:互联网 发布:minidao sql 编辑:程序博客网 时间:2024/06/01 10:27

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
原创粉丝点击