题解 | #合并两个排序的链表#

合并两个排序的链表

https://www.nowcoder.com/practice/d8b6b4358f774294a89de2a6ac4d9337

/**
 * struct ListNode {
 *	int val;
 *	struct ListNode *next;
 * };
 */

/**
 * 
 * @param pHead1 ListNode类 
 * @param pHead2 ListNode类 
 * @return ListNode类
 */
#include <stdlib.h>
struct ListNode* Merge(struct ListNode* pHead1, struct ListNode* pHead2 ) {
    // write code here
    if( !pHead1 ){
        return pHead2;
    }
    if( !pHead2 ){
        return pHead1;
    }
    struct ListNode *p = (struct ListNode *)malloc(sizeof(struct ListNode));
    struct ListNode *q ;
    if(pHead1->val >= pHead2->val){
        p = pHead2;
        pHead2 = pHead2->next;
    }
    else {
        p = pHead1;
        pHead1 = pHead1->next;
    }
    q = p;
    while (pHead1 && pHead2) {
        if(pHead1->val >= pHead2->val){
            q->next = pHead2;
            pHead2 = pHead2->next;
        }
        else if(pHead1->val < pHead2->val){
            q->next = pHead1;
            pHead1 = pHead1->next;
        }
        q = q->next;
    }
    if(!pHead1){
        q->next = pHead2;
    }
    else {
        q->next = pHead1;
    }
    return p;
}

#刷题记录#
全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务