LeetCode 21. Merge two ordered linked lists (single linked lists)

Keywords: network

Article directory

1. Topic information

Merge the two ordered lists into a new ordered list and return. The new linked list is composed of all the nodes of a given two linked list.

Example:

Input: 1 - > 2 - > 4, 1 - > 3 - > 4
 Output: 1 - > 1 - > 2 - > 3 - > 4 - > 4

Source: LeetCode
Link: https://leetcode-cn.com/problems/merge-two-sorted-lists
Copyright belongs to the seizure network. For commercial reprints, please contact the official authorization. For non-commercial reprints, please indicate the source.

2. solving problems

  • The basic operation of linked list, pay attention to connect the previous node and the next node (l1,l2 in the current position of the smaller) together

/**
 * 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) {
        if(l1 == NULL)
            return l2;
        else if(l2 == NULL)
            return l1;
        else
        {
            ListNode *newHead = new ListNode(0);
            ListNode *curNode = newHead->next, *prev = newHead;
            while(l1 && l2)
            {
                if(l1->val < l2->val)
                {
                    curNode = l1;
                    l1 = l1->next;
                }
                else
                {
                    curNode = l2;
                    l2 = l2->next;
                }
                prev->next = curNode;
                prev = curNode;
                curNode = curNode->next;

            }
            if(l1 == NULL)
            {
                while(l2)
                {
                    curNode = l2;
                    l2 = l2->next;
                    prev->next = curNode;
                    prev = curNode;
                    curNode = curNode->next;    
                }
            }
            else//l2 == NULL
            {
                while(l1)
                {
                    curNode = l1;
                    l1 = l1->next;
                    prev->next = curNode;
                    prev = curNode;
                    curNode = curNode->next;
                }
            }
            return newHead->next;
        }        
    }
};

Posted by FRSH on Sat, 05 Oct 2019 22:02:26 -0700