合并排序链表

1.迭代实现

class Solution {
public:
    ListNode* Merge(ListNode* pHead1, ListNode* pHead2)
    {
      auto res=pHead1;
      ListNode* pre=0;
      auto h1=pHead1,h2=pHead2;
      for(;h1&&h2;)
      {
        if(h1->val>=h2->val)
        {
          if(pre==0)
          { auto temp=h2->next;
            h2->next=h1;
            pre=h2;
            res=h2;
            h2=temp;
          }
          else
          {
            auto temp=h2->next;
            pre->next=h2;
            h2->next=h1;
            pre=h2;
            h2=temp;
          }

        }
        else
        {
          pre=h1;
          h1=h1->next;
        }
      }

      if(h1==0&&h2!=0)
      {
        pre->next=h2;
      }

      return res;


    }
};

2.递归实现

class Solution {
public:
    ListNode* Merge(ListNode* pHead1, ListNode* pHead2)
    {
      if(pHead1==0)return pHead2;
      if(pHead2==0)return pHead1;
      if(pHead1->val>=pHead2->val)
      {
        pHead2->next=Merge(pHead1,pHead2->next);
        return pHead2;
      }
        else
        {
          pHead1->next=Merge(pHead1->next,pHead2);
          return pHead1;
        }

    }
};
全部评论

相关推荐

不愿透露姓名的神秘牛友
07-02 15:39
点赞 评论 收藏
分享
认真搞学习:28小登的建议,投算法岗不要写什么物理竞赛,互联网+,多写点项目,用什么算法做了什么。还有本科算法是不可能的开发你这个也没有项目啊
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
07-03 16:22
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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