leetcode (21) - Merge Two Sorted Lists

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


/**
 * 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 && !l2) return l1;
    if(!l1 && l2) return l2;
    
    struct ListNode* p1=l1;
    struct ListNode* p2=l2;
    struct ListNode* ret_head=malloc(sizeof(struct ListNode));
    struct ListNode* ret_p=ret_head;
    ret_p->next=NULL;
    if(p1->val > p2->val){
        ret_p->val=p2->val;
        p2=p2->next;
    } else {
        ret_p->val=p1->val;
        p1=p1->next;
    }
    
    struct ListNode* new_node;
    while(p1 && p2){
        new_node=malloc(sizeof(struct ListNode));
        new_node->next=NULL;
        
        if(p1->val > p2->val){
            new_node->val=p2->val;
            p2=p2->next;
        } else {
            new_node->val=p1->val;
            p1=p1->next;
        }
        
        ret_p->next=new_node;
        ret_p=new_node;
        
    }
    
    while(p1){
        new_node=malloc(sizeof(struct ListNode));
        new_node->next=NULL;
        new_node->val=p1->val;
        p1=p1->next;
        ret_p->next=new_node;
        ret_p=new_node;
    }
    
    while(p2){
        new_node=malloc(sizeof(struct ListNode));
        new_node->next=NULL;
        new_node->val=p2->val;
        p2=p2->next;
        ret_p->next=new_node;
        ret_p=new_node;
    }
    
    return ret_head;
}


發佈了23 篇原創文章 · 獲贊 19 · 訪問量 42萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章