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

合并两个排序的链表

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

/**
 * struct ListNode {
 *	int val;
 *	struct ListNode *next;
 *	ListNode(int x) : val(x), next(nullptr) {}
 * };
 */
class Solution {
public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param pHead1 ListNode类 
     * @param pHead2 ListNode类 
     * @return ListNode类
     */
    ListNode* Merge(ListNode* pHead1, ListNode* pHead2) {
        // write code here
        if(pHead1 == nullptr || pHead2 == nullptr) return pHead1==nullptr ?pHead2 :pHead1;
        ListNode* head = pHead1->val <= pHead2->val ? pHead1 : pHead2;
        ListNode* cur1 = head->next;
        ListNode* cur2 = head == pHead1 ? pHead2 : pHead1;
        ListNode* pre = head;
        while(cur1!=nullptr && cur2!=nullptr) {
            if(cur1->val <= cur2->val) {
                pre->next =cur1;
                cur1=cur1->next;
            } else{
                pre->next =cur2;
                cur2=cur2->next;
            }
            pre = pre->next;
        }
        pre->next = cur1!=nullptr ? cur1 : cur2;
        return head;
    }
};

//         ↓cur2
// List1    2     4      6

//         ↓cur1
// List2    1     3      5      7     8


// ↓
// head(pre)

全部评论

相关推荐

不愿透露姓名的神秘牛友
07-01 10:56
点赞 评论 收藏
分享
认真搞学习:28小登的建议,投算法岗不要写什么物理竞赛,互联网+,多写点项目,用什么算法做了什么。还有本科算法是不可能的开发你这个也没有项目啊
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
06-11 13:34
offe从四面八方来:我真的没时间陪你闹了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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