• 17 合并两个排序的链表


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

    C++:迭代

     1 /*
     2 struct ListNode {
     3     int val;
     4     struct ListNode *next;
     5     ListNode(int x) :
     6             val(x), next(NULL) {
     7     }
     8 };*/
     9 class Solution {
    10 public:
    11     ListNode* Merge(ListNode* pHead1, ListNode* pHead2)
    12     {
    13         if (pHead1 == NULL)
    14             return pHead2 ;
    15         if (pHead2 == NULL)
    16             return pHead1 ;
    17         ListNode* pHead = NULL ;
    18         if (pHead1->val <= pHead2->val){
    19             pHead = pHead1 ;
    20             pHead1 = pHead1->next ;
    21         }else{
    22             pHead = pHead2 ;
    23             pHead2 = pHead2->next ;
    24         }
    25         ListNode* p = pHead ;
    26         while(pHead1 != NULL && pHead2 != NULL){
    27             if (pHead1->val <= pHead2->val){
    28                 p->next = pHead1 ;
    29                 pHead1 = pHead1->next ;
    30             }else{
    31                 p->next = pHead2 ;
    32                 pHead2 = pHead2->next ;
    33             }
    34             p = p->next ;
    35         }
    36         if (pHead1 != NULL)  p->next = pHead1 ;
    37         if (pHead2 != NULL)  p->next = pHead2 ;
    38         return pHead ;
    39     }
    40 };

    C++:递归

     1 /*
     2 struct ListNode {
     3     int val;
     4     struct ListNode *next;
     5     ListNode(int x) :
     6             val(x), next(NULL) {
     7     }
     8 };*/
     9 class Solution {
    10 public:
    11     ListNode* Merge(ListNode* pHead1, ListNode* pHead2)
    12     {
    13         if (pHead1 == NULL)
    14             return pHead2 ;
    15         if (pHead2 == NULL)
    16             return pHead1 ;
    17         if (pHead1->val <= pHead2->val){
    18             pHead1->next = Merge(pHead1->next , pHead2) ;
    19             return pHead1 ;
    20         }else{
    21             pHead2->next = Merge(pHead1 , pHead2->next) ;
    22             return pHead2 ;
    23         }
    24     }
    25 };
  • 相关阅读:
    Html笔记(四)图像
    Html笔记(三)列表
    Html笔记(二)字体
    Html笔记(一)概述
    mysql基础~经典题目
    MGR架构~原理细节分析(8.0最新版)
    hiveserver2
    恋爱心理
    和谐之道
    智者遇事求心,庸者遇事求境
  • 原文地址:https://www.cnblogs.com/mengchunchen/p/8940003.html
Copyright © 2020-2023  润新知