LeeCode-合并两个有序链表

题解 迭代法

  画图可以容易想到迭代的方法。要注意的是,需要设置一个指针(head),记录合成链表最开始的位置。还需要维护一个具有next指针的元素(temp),实时更新位置,所以要new一个和结点结构一样的元素。

#include "iostream"
using namespace std;
class Solution {
public:
     ListNode* mergeTwoLists(ListNode* l1, 	ListNode* l2) {
         if(l1==NULL) return l2;
         if(l2==NULL) return l1;
         ListNode *temp=new ListNode(-100);
         ListNode *head=temp;
         while(l1!=NULL && l2!=NULL)
         {
             if(l1->val<=l2->val)
             {
                 temp->next=l1;
                 temp=l1;
                 l1=l1->next;
             }
             else
             {
                 temp->next=l2;
                 temp=l2;
                 l2=l2->next;
             }
         }
         if(l2==NULL) temp->next=l1;
         if(l1==NULL) temp->next=l2;

        return head->next;
    }
};

#题解:递归方法
  先比较头结点,小的节点作为新链表的首结点,然后把新结点的下一个结点作为新链表的第一个结点,与另一个链表作为参数,再次调用函数,以此递归。递归结束的条件是一个链表减为0。
  不知道为什么同样的代码在vscode上提交显示超时,在网页LeetCode就提交成功…md

 #include "iostream"
 using namespace std;
 
 struct ListNode {
      int val;
      ListNode *next;
      ListNode(int x) : val(x), next(NULL) {}
  };

class Solution {
public:
	ListNode* mergeTwoLists(ListNode* l1, 	ListNode* l2) {
	    if(l1==NULL) return l2;
	    if(l2==NULL) return l1;

	    if(l1->val<l2->val)
	    {
	        l1->next=mergeTwoLists(l1-	>next,l2);
	        return l1;
	    }
	    l2->next=mergeTwoLists(l1,l2->next);
	    return l2;

	}
};
发布了36 篇原创文章 · 获赞 0 · 访问量 599

猜你喜欢

转载自blog.csdn.net/weixin_43199933/article/details/105001544
今日推荐