Combine two sorted linked lists-basic linked list operations

Merge two sorted linked lists

Enter two linked lists in ascending order, merge the two linked lists and make the nodes in the new linked list still in ascending order.

Example 1:

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

0 <= length of linked list <= 1000


solution

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */


struct ListNode* mergeTwoLists(struct ListNode* l1, struct ListNode* l2){
    
    
    // 考虑代码的鲁棒性
    if(!l1 && !l2)
        return NULL;
    if(!l1)
        return l2;
    if(!l2)
        return l1;
    // 新链表指向最小值的头节点
    struct ListNode *new_l = l1->val > l2->val ? l2 : l1;
    struct ListNode *p = new_l;
    // 移动
    if(l1->val <= l2->val){
    
    
        l1 = l1->next;
    }else{
    
    
        l2 = l2->next;
    }

    while(l1 && l2){
    
    
        // 当l1和l2都不为空时,进行比较
        if(l1->val <= l2->val){
    
    
            p->next = l1;
            p = p->next;
            l1 = l1->next;
        }else{
    
    
            p->next = l2;
            p = p->next;
            l2 = l2->next;
        }        
    }
    // 如果l1空了
    if(!l1)
        p->next = l2;
    if(!l2)
        p->next = l1;
    return new_l;
}

Guess you like

Origin blog.csdn.net/qq_39378657/article/details/109616485