zoukankan      html  css  js  c++  java
  • 合并两个排序的链表

    时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 32M,其他语言64M 

    题目描述

    输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。
     
    思路:
      一、设立pPoint1指向第一个链表,pPoint2指向第二个链表,newPoint作为新链表的指针,比较pPoint1与pPoint2指针所指数据的大小,确定链表的next的指向
    注:ListNode* pPoint1的指针的引用为ListNode*& pPoint1
    /*
    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 == NULL)
                return pHead2;
            if(pHead2 == NULL)
                return pHead1;
            ListNode *pPoint1 = pHead1;
            ListNode *pPoint2 = pHead2;
            ListNode *newPoint ,*newPointTemp;
             
            newPoint = isMin(pPoint1,pPoint2);
           
            newPointTemp = newPoint;
             
            while(pPoint1 != NULL && pPoint2!= NULL)
            {
                newPointTemp->next = isMin(pPoint1,pPoint2);
                newPointTemp = newPointTemp->next;
            }
            if(pPoint1 == NULL )
                newPointTemp->next = pPoint2;
             else
                 newPointTemp->next = pPoint1;
            return newPoint;
        }
         ListNode* isMin(ListNode*& pPoint1,ListNode*& pPoint2)
        {
             ListNode *temp;
             if(pPoint1->val <= pPoint2->val)
                {
                    temp = pPoint1;
                    pPoint1 = pPoint1->next;
                     
                }
                else
                {
                    temp = pPoint2;
                    pPoint2 = pPoint2->next;
                
                }
             return temp;
        }
    };

    二、采用递归的方式,较难理解

    /*
    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 == NULL)
                return pHead2;
            if(pHead2 == NULL)
                return pHead1;
            
            if(pHead1->val <= pHead2->val)
            {
                pHead1->next = Merge(pHead1->next,pHead2);
                return pHead1;
            }
            else
            {
                pHead2->next = Merge(pHead1,pHead2->next);
                return pHead2;
            }
        }
    };
  • 相关阅读:
    vbs实现c++的vector
    二叉树的线索化及其遍历(必会)
    二叉树的7种遍历(必背)
    PyQt5发布技巧:指定插件(plugins)路径
    pyqt5环境变量踩坑记
    怎样把ndarray转换为PyQt中的QPixmap
    桌面应用“标注器”打包踩坑记
    怎样用cmd脚本添加Qt的环境变量
    Krpano动态热点添加始终显示的文字
    VS解决方案中个文件类型含义
  • 原文地址:https://www.cnblogs.com/whiteBear/p/12506098.html
Copyright © 2011-2022 走看看