将两个升序链表合并为一个升序链表

将两个升序链表合并为一个升序链表。

方法①:递归

struct ListNode
{
  int val;
  ListNode* next;
  ListNode(int x):val(x),next(NULL){}
};
class Solution
{ 
   public:
      ListNode* mergeList(ListNode* l1, ListNode* l2)
      {
        if(l1==NULL) return l2;
        if(l2==NULL) return l1;
        ListNode* head;
        if(l1->val < l2->val)
        {
          head=l1;
          head->next=mergeList(l1->next, l2);
        }
        else
        {
          head=l2;
          head->next=mergeList(l1, l2->next);
        }
        return head;
      }
}

②迭代

class Solution
{
  public:
     ListNode* mergeList(ListNode* l1,ListNode* l2)
     {
       if(l1==NULL) return l2;
       if(l2==NULL) return l1;
       ListNode* head=new ListNode(0);
       ListNode* p=head;
       while(l1 && l2)
       {
         if(l1->val < l2->val)
         {
           p->next=l1;
           l1=l1->next;
           p=p->next;
         }
         else
         {
           p->next=l2;
           l2=l2->next;
           p=p->next;
         }
       }
       p->next=l1?l1:l2;
       return head->next;
     }
}
发布了22 篇原创文章 · 获赞 1 · 访问量 347

猜你喜欢

转载自blog.csdn.net/weixin_43086349/article/details/104641596