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

合并两个排序的链表

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

/**
 * struct ListNode {
 *	int val;
 *	struct ListNode *next;
 * };
 */
/**
 * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
 *
 * 
 * @param pHead1 ListNode类 
 * @param pHead2 ListNode类 
 * @return ListNode类
 */
#include <stdio.h>
struct ListNode* Merge(struct ListNode* pHead1, struct ListNode* pHead2 ) {
    // write code here
    if(pHead1 == NULL)//如果表1为空
    {
        return pHead2;
    }
    if(pHead2 == NULL)//表2为空
    {
        return pHead1;
    }
    struct ListNode* pHead = pHead1;//这个是合并表
    if (pHead1->val <= pHead2->val)//两个链表中的第一个数据比较,也就是pHead的第一个数据
    {
        pHead1 = pHead1->next;
    }
    else {
        pHead = pHead2;
        pHead2 = pHead2->next;
    }
    struct ListNode* pCurrent = pHead;//遍历使用
    while(pHead1 != NULL && pHead2 != NULL){

            if(pHead1->val <= pHead2->val){//如果表1中的数据小于表2

                pCurrent->next = pHead1;

                pHead1 = pHead1->next;

            }
            else{//表1数据大于表2

                pCurrent->next = pHead2;

                pHead2 = pHead2->next;

            }

            pCurrent = pCurrent->next;//继续向后遍历      

        }
        //最后一个元素的判断
        if(pHead1){

            pCurrent->next = pHead1;

        }
        if(pHead2){

            pCurrent->next = pHead2;

        }
        return pHead;//返回合并表

    }



C语言基础 文章被收录于专栏

里面较为详细的介绍了c语言的相关用法和有关题目。

全部评论

相关推荐

2025-12-15 14:25
云南大学 Java
lei22:入职可能会看学信网,最好别伪装,这个简历找实习肯定是够的,肯定会有收 28 届实习生的公司的,多投就行
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务