21. 合并两个有序链表 力扣(简单) 链表练习

题目描述:

将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。 

示例 1:

输入:l1 = [1,2,4], l2 = [1,3,4]
输出:[1,1,2,3,4,4]

题源:https://leetcode-cn.com/problems/merge-two-sorted-lists/

代码:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
     ListNode* head;
     if (l1==NULL) return l2;  // 边界条件需要注意,经常遗忘
     if (l2==NULL) return l1;
     if(l1->val<=l2->val)
         {head=l1; l1=l1->next;}
     else {head=l2; l2=l2->next;}
     ListNode* cur=head;
     while(l1!=NULL && l2!=NULL)
     {
         if(l1->val<=l2->val)
         {
             cur->next=l1;
             cur=cur->next;  // 老是忘记往后挪一位
             l1=l1->next;
         } else{
             cur->next=l2;
             cur=cur->next;
             l2=l2->next;
         }
     }
     if(l1==NULL) cur->next=l2;
       else cur->next=l1;
     return head;
    }
};

 

posted on 2021-07-25 22:00  Yxter  阅读(25)  评论(0编辑  收藏  举报

导航