Sword refers to Offer series Sword refers to Offer 25: merge two ordered linked lists

Title description:

Combine the two ascending linked lists into a new  ascending  linked list and return. The new linked list is composed by splicing all the nodes of the given two linked lists.

Example:

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

Problem-solving ideas:

  1. Because the two linked lists are in order, we directly determine the value of a node in the two linked lists in a loop, which one is smaller and which one moves one bit backward, until the end of a linked list.
  2. Just follow the rest of the linked list that has not been judged to end.

Code:

class Solution {
public:
    ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
        ListNode* pp = new ListNode(0);
        auto p = pp;
        while(l1 && l2)
        {
            if(l1->val > l2->val){
                p->next = l2;
                p = p->next;
                l2 = l2->next;
            }
            else{
                p->next = l1;
                p=p->next;
                l1 = l1->next;
            }
        }
        if(l1){ p->next = l1;}
        else{ p->next = l2;}
        pp = pp->next;
        return pp;
    }
};

 

Guess you like

Origin blog.csdn.net/qq_46423166/article/details/110790639