21 merge two sorted lists

申请一个dummy头,依次从头比较两个链表,谁小就插入到 dummy,对应指针后移

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
struct ListNode* mergeTwoLists(struct ListNode* l1, struct ListNode* l2) {

    struct ListNode *dummyhead = malloc(sizeof(struct ListNode));
    dummyhead->next = NULL;
    struct ListNode *lastnode = dummyhead;

    while(1){
        if(l1&&l2){
            if(l1->val < l2->val){
                lastnode->next = l1;
                l1 = l1->next;
                lastnode = lastnode->next;
            }else{
                lastnode->next = l2;
                l2 = l2->next;
                lastnode = lastnode->next;
            }
        }else if(l1){
            lastnode->next = l1;
            break;
            
        }else if(l2){
            lastnode->next = l2;
            break;
        }else
            break;
    }

    struct ListNode *tmp = dummyhead->next;
    free(dummyhead);
    return tmp;

}

你可能感兴趣的:(21 merge two sorted lists)