zoukankan      html  css  js  c++  java
  • 剑指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 节点,可以避免很多麻烦的事情。

     
     
  • 相关阅读:
    ArtTmeplate模板+取结接口
    取接口
    ionic 基本布局
    angular通过路由实现跳转 resource加载数据
    总结
    JSON和JSONP
    js中sort()方法的用法,参数以及排序原理
    计算机语言的发展史
    Jquery+PHP实现简单的前后台数据交互实现注册登录,添加留言功能
    Jquery回调函数应用实例解析
  • 原文地址:https://www.cnblogs.com/dingxiaoqiang/p/7467541.html
Copyright © 2011-2022 走看看