Leetcode Merge Two Sorted Lists 日常刷题

/**
 * 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 *head=new ListNode(-1);
        ListNode *move = head;
        if (l1 == NULL) return l2;
        if (l2 == NULL) return l1;
        while (l1 != NULL && l2 != NULL)
        {
            if (l1->val < l2->val)
            {
                move->next = l1;
                l1 = l1->next;
            }
            else 
            {
                move->next = l2;
                l2 = l2->next;
            }
            move = move->next;
        }
        while (l1 != NULL)
        {
            move->next = l1;
            l1 = l1->next;
            move = move->next;
        }
        while (l2 != NULL)
        {
            move->next = l2;
            l2 = l2->next;
            move = move->next;
        }
        return head->next;
    }
};

刷题总结:

新创建一个Listnode类head,用move在head上移动。

       具体思想就是新建一个链表,然后比较两个链表中的元素值,把较小的那个链到新链表中,由于两个输入链表的长度可能不同,所以最终会有一个链表先完成插入所有元素,则直接另一个未完成的链表直接链入新链表的末尾。

猜你喜欢

转载自blog.csdn.net/weixin_43965572/article/details/89738600