banner
ekko

ekko's blog

时间不在于你拥有多少,而在于你怎样使用
github
xbox
email

Merge Two Sorted Lists

Description#

Merge two sorted lists into a new sorted list and return it. The new list should be made by splicing together the nodes of the given two lists.

Example:

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

Approach#

  • When one of the lists is empty, return the other list, regardless of whether the other list is empty or not.
  • Set the list with the smaller first element as the list to be inserted, and the other list as the list to insert. The list to be inserted is the final list to be returned.
  • While the current list to insert is not empty or the list to be inserted still has a next element, if the element of the list to insert is not greater than the next element of the list to be inserted, insert it before the next element. Otherwise, move the current list to insert forward.
  • When there are still elements in the list to insert (when there is a number greater than the last element of the list to be inserted, it will not be inserted in the previous process), it needs to be directly appended after the list to be inserted.
struct ListNode* mergeTwoLists(struct ListNode* l1, struct ListNode* l2){
    struct ListNode* l_get_buffer,*l_set_buffer,*l_final,*l_get,*l_set;
    //When one of the lists is empty
    if(!(l1 && l2)) {
        return l1?l1:l2;//Return l1 if l1 is not empty, otherwise return l2
    }
    //Set the list with the smaller first element as the list to be inserted
    l_set = (l1->val <= l2->val)?l1:l2;
    l_get = (l_set == l1)?l2:l1;
    //The final list to be returned is the list with the smaller first element
    l_final = l_set;
    while (l_get != 0 && l_set->next != 0)
    {
        if((l_get->val) <= (l_set->next->val))  {
            //Record the current two pointers
            l_get_buffer = l_get;
            l_set_buffer = l_set;
            //Update the next pointer
            l_get = l_get->next; 
            //Reorganize the pointers
            l_get_buffer->next = l_set_buffer->next;
            l_set_buffer->next = l_get_buffer; 
        }  
        else 
            l_set = l_set->next;
    }
    //There are remaining elements to be inserted
    if(l_get != 0)
        l_set->next = l_get;
    return l_final;
}

Note#

  • When inserting elements, the pointer of the list to be inserted should not move forward, otherwise it will miss the comparison of one element of the list to be inserted.
Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.