[leetcode] 21 合并两个有序链表

问题描述

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

示例

输入:1->2->4, 1->3->4
输出:1->1->2->3->4->4

模版

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
    }
};

解题思路

头节点经典问题,合并出来的新链表需要先建立一个头节点,然后最后输出头节点的下一个节点即可。递归和迭代都可以解决这个题。

完整代码

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
        ListNode* l3=new ListNode(0);
        ListNode* currentNode3=l3;
        while(l1!=nullptr && l2!=nullptr){
            if(l1->val>l2->val){
                currentNode3->next=l2;
                l2=l2->next;
            }
            else {
                currentNode3->next=l1;
                l1=l1->next;
            }
            currentNode3=currentNode3->next;
        }
        currentNode3->next=(l1==nullptr?l2:l1);
        return l3->next;
    }
};
原创文章 61 获赞 58 访问量 6383

猜你喜欢

转载自blog.csdn.net/weixin_43347376/article/details/105874467