题解 | #合并两个排序的链表#

合并两个排序的链表

https://www.nowcoder.com/practice/d8b6b4358f774294a89de2a6ac4d9337

插入法

/**
 * struct ListNode {
 *	int val;
 *	struct ListNode *next;
 * };
 */

/**
 * 
 * @param pHead1 ListNode类 
 * @param pHead2 ListNode类 
 * @return ListNode类
 */
struct ListNode* Merge(struct ListNode* pHead1, struct ListNode* pHead2 ) 
{
    if(pHead1==NULL)
        return pHead2;
    if(pHead2==NULL)
        return pHead1;
    struct ListNode * t;
    struct ListNode * ans;
    if(pHead1->val>pHead2->val)
    {
        t=pHead1;
        pHead1=pHead2;
        pHead2=t;
    }
    ans=pHead1;
    while(pHead1->next&&pHead2)
    {
        if(pHead1->next->val>pHead2->val)
        {
            t=pHead2;
            pHead2=pHead2->next;
            t->next=pHead1->next;
            pHead1->next=t;
        }
        pHead1=pHead1->next;
    }
    if(pHead1->next==NULL)
        pHead1->next=pHead2;
    return ans;
}

迭代法(创建一个新链表)

/**
 * struct ListNode {
 *	int val;
 *	struct ListNode *next;
 * };
 */

/**
 * 
 * @param pHead1 ListNode类 
 * @param pHead2 ListNode类 
 * @return ListNode类
 */
struct ListNode* Merge(struct ListNode* pHead1, struct ListNode* pHead2 )
{
    struct ListNode * cur;
    struct ListNode * result=(struct ListNode *)malloc(sizeof(struct ListNode));//创建一个新的头节点
    cur=result;
    while(pHead1&&pHead2)//这种方式要记住
   {
        if(pHead1->val<=pHead2->val) //哪个链表头节点小从哪个链表拿
            {
                cur->next=pHead1; //取节点
                pHead1=pHead1->next;//后移对应链表
            }
            else//同理
            {
                cur->next=pHead2;
                pHead2=pHead2->next;
            }
            cur=cur->next;//将新链表后移
   }
    if(pHead2==NULL) //将剩余的链表拼在后面(这个思路重点)
         cur->next=pHead1;
    if(pHead1==NULL)
         cur->next=pHead2;
        return result->next;
}

全部评论

相关推荐

深夜书店vv:腾讯是这样的,去年很多走廊都加桌子当工区
点赞 评论 收藏
分享
07-07 12:25
门头沟学院 Java
程序员牛肉:你这个智邮公司做的就是那个乐山市税务系统的服务吗?
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务