• [剑指offer] 合并两个排序的链表


    题目描述

    输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。

    思路比较简单,主要是对指针的操作要考虑完全。

    /*
    struct ListNode {
        int val;
        struct ListNode *next;
        ListNode(int x) :
                val(x), next(NULL) {
        }
    };*/
    class Solution {
    public:
        ListNode* Merge(ListNode* pHead1, ListNode* pHead2)
        {
            if (!pHead1 && !pHead2) return NULL;
            if (!pHead1) return pHead2;
            if (!pHead2) return pHead1;
            ListNode* re, *result;    // re不断更新来向尾部创建节点,result存储头指针
            if (pHead1->val > pHead2->val) {
                re = new ListNode(pHead2->val);
                pHead2 = pHead2->next;
            } else {
                re = new ListNode(pHead1->val);
                pHead1 = pHead1->next;
            }
            result = re;
            while (pHead1 || pHead2) {
                if (pHead1 && pHead2) {
                    if ((pHead1->val) > (pHead2->val)) {
                        re->next = new ListNode(pHead2->val);
                        pHead2 = pHead2->next;
                    } else {
                        re->next = new ListNode(pHead1->val);
                        pHead1 = pHead1->next;
                    }
                    re = re->next;
                } else if (pHead1) {
                    while (pHead1) {
                        re->next = new ListNode(pHead1->val);
                        pHead1 = pHead1->next;
                        if (pHead1) re = re->next;
                    }
                } else {
                    while (pHead2) {
                        re->next = new ListNode(pHead2->val);
                        pHead2 = pHead2->next;
                        if (pHead2) re = re->next;
                    }
                }
            }
            return result;
        }
    };
  • 相关阅读:
    字符串和数字的相互转换
    考研_计算机网络
    修改Win+E映射
    BFS总结
    关于—— !important
    css中hack是什么
    轮播图 Swiper4.x 代码模板
    微信小程序---数组操作
    小程序-----button 分享按钮
    微信小程序从子页面退回父页面时的数据传递 wx.navigateBack()
  • 原文地址:https://www.cnblogs.com/zmj97/p/7904998.html
Copyright © 2020-2023  润新知