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


    题目描述:

    输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。
    这题说明自己对链表还是不熟悉。
     
     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         if(pHead1 == nullptr && pHead2 == nullptr){
    13             return nullptr;
    14         }
    15         if(pHead1 == nullptr){
    16             return pHead2;
    17         }
    18         if(pHead2 == nullptr){
    19             return pHead1;
    20         }
    21         ListNode* pHead = new ListNode(0);
    22         ListNode* head = pHead;
    23         
    24         while(pHead1 != nullptr && pHead2 != nullptr){
    25             if(pHead1 -> val < pHead2 -> val){
    26                 pHead -> next= pHead1;
    27                 pHead1 = pHead1 -> next;
    28             }
    29             else{
    30                 pHead -> next = pHead2;
    31                 pHead2 = pHead2 -> next;
    32             }
    33             
    34             pHead = pHead -> next;
    35         }
    36         if(pHead1 != nullptr){
    37             pHead -> next = pHead1;
    38         }
    39         if(pHead2 != nullptr){
    40             pHead -> next = pHead2;
    41         }
    42         return head -> next;
    43     }
    44 };

    开始自己写的时候,将

    while(pHead1 != nullptr && pHead2 != nullptr){
                if(pHead1 -> val < pHead2 -> val){
                    pHead = pHead1;
                    pHead1 = pHead1 -> next;
                }
                else{
                    pHead = pHead2;
                    pHead2 = pHead2 -> next;
                }
                
                pHead = pHead -> next;
            }

    这样并没有改变结果,相当于将head指向了pHead1,并没有改变原来的指向关系。只有 p = p -> next,才能改变指向关系。新建一个dummy node 节点,可以避免很多麻烦的事情。

     
     
  • 相关阅读:
    不是结束,而是刚刚开始
    第七次作业
    用类做封装
    用户故事
    团队编程--MP3播放器
    结对编程作业
    四则运算
    四、小电视自动抽奖
    三、wss连接B站弹幕
    一、基础设计
  • 原文地址:https://www.cnblogs.com/dingxiaoqiang/p/7467541.html
Copyright © 2020-2023  润新知