Link exercises <Merge two ordered linked lists>

Lituo No. 21 question, description of the question:

Merges two ascending lists into a new ascending list and returns. The new linked list is formed by splicing all the nodes of the given two linked lists.

Example 1:
Input: l1 = [1,2,4], l2 = [1,3,4]
Output: [1,1,2,3,4,4]
Example 2:

Input: l1 = [], l2 = []
Output: []
Example 3:

Input: l1 = [], l2 = [0]
Output: [0]
Prompt: The range of the number of nodes in the two linked lists is [0, 50]
-100 <= Node.val <= 100
l1 and l2 are in non-decreasing order Sorting source: LeetCode
Link: https://leetcode-cn.com/problems/merge-two-sorted-lists
The copyright belongs to LeetCode. For commercial reprints, please contact the official authorization, for non-commercial reprints, please indicate the source.

I used a method similar to double pointers to solve this problem. Finally, when I returned to the linked list, I found that there was always an extra head. I was still thinking about how to remove the 0 in this head. Finally, I thought that it would be fine to just return to its next. . . Still too good

/**
 * 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* list1, ListNode* list2) {
        if(list1==NULL) return list2;
        if(list2==NULL) return list1;
        ListNode* result = new ListNode;  //注意不能返回局部变量,所以要申请地址
        ListNode* p = result;               //借助P来完成遍历的操作
        ListNode* l1 = list1;
        ListNode* l2 = list2;
        while(l1!=NULL && l2!= NULL)
        {   
           if(l1->val <= l2->val )
           {
               p->next = l1;
               p = p->next;
               l1 = l1->next;
           }else if(l1->val > l2->val )
           {
               p->next = l2;
               p = p->next;
               l2 = l2->next;
           }     
        }
        if(l1 == NULL)
        {
            p->next = l2;
            return result->next;
        }else if(l2 == NULL)
        {
            p->next = l1;
            return result->next;
        }
        return result->next;                                  
    }
};

You can also use recursion, very violent

class Solution {
public:
/*方法二:直接递归 */
    ListNode* mergeTwoLists(ListNode* list1, ListNode* list2) {
        if(list1==NULL) return list2;
        if(list2==NULL) return list1;
        if(list1->val < list2->val)
        {
            list1->next = mergeTwoLists(list1->next,list2); 
//可以这么理解,因为这个函数得到的就是一个升序合并后的链表,所以直接让小的接上他  
            return list1;
        }else
        {
            list2->next = mergeTwoLists(list1,list2->next);
            return list2;
        }
    }
};

 

Guess you like

Origin blog.csdn.net/mc10141222/article/details/123766361