• 合并两个排序的链表


    题目描述

    输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。
     
    非递归版本:
    1.新建一个头结点mergeHead,和尾节点 current.
    2.比较两个链表的头节点,确定mergeHead, 将current指向mergeHead.
    3.依次比较两个链表节点(在都不为空的情况下),current->next保存数值小的节点, current后移
    4.若链表为空, current->next指向 非空链表
    5.返回mergeHead.
    /*
    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 == nullptr)
            return pHead2;
        if(pHead2 == nullptr)
            return pHead1;
        
        ListNode * mergeHead = nullptr; //新建一个头结点mergeHead,和尾节点 current.
        ListNode * current = nullptr;
        if(pHead1->val <= pHead2->val)  //比较两个链表的头节点,确定mergeHead
        {                                //将current指向mergeHead.
            mergeHead =  current =pHead1;
            pHead1 = pHead1->next;
        }
        else
        {
            mergeHead = current = pHead2;
            pHead2 = pHead2->next;
        }
        
        while(pHead1!=NULL && pHead2!=NULL) //遍历两个链表
        {
            if(pHead1->val <= pHead2->val)  
            {
                current->next = pHead1;  //current保存小的节点
                current = current->next; //current后移
                pHead1 = pHead1->next;   //该链表后移
            }
            else
            {
                current->next = pHead2;
                current = current->next;
                pHead2 = pHead2->next;
            }
        }
        if(pHead1 == NULL)
        {
            current->next = pHead2;
        }
        if(pHead2 == NULL)
        {
            current->next = pHead1;
        }
        return mergeHead;   
        }
    };
  • 相关阅读:
    虚拟化碎片知识
    CentOS升级内核及KVM安装(已试验,可行)
    Libvirt 虚拟化库剖析
    [ACM]Max Sum
    [ACM]n a^o7 !
    [java]ActionEvent事件:获取输入字符串的长度
    [ACM]The Best Seat in ACM Contest
    [java]ItemEvent事件:简单计算器
    通过注册表的句柄得到当前句柄在注册表中的路径
    [测试模式]Setup方法的滥用
  • 原文地址:https://www.cnblogs.com/zmm1996/p/11902428.html
Copyright © 2020-2023  润新知