• 21. Merge Two Sorted Lists【easy】


    21. Merge Two Sorted Lists【easy】

    Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.

    解法一:

     1 /**
     2  * Definition for singly-linked list.
     3  * struct ListNode {
     4  *     int val;
     5  *     ListNode *next;
     6  *     ListNode(int x) : val(x), next(NULL) {}
     7  * };
     8  */
     9 class Solution {
    10 public:
    11     ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
    12         if (l1 == NULL || l2 == NULL) {
    13             return l1 ? l1 : l2;
    14         }
    15         
    16         ListNode * dummy = new ListNode(INT_MIN);
    17         ListNode * temp = dummy;
    18         
    19         while (l1 && l2) {
    20             if (l1->val > l2->val) {
    21                 dummy->next = l2;
    22                 l2 = l2->next;
    23             }
    24             else {
    25                 dummy->next = l1;
    26                 l1 = l1->next;
    27             }
    28             
    29             dummy = dummy->next;
    30         }
    31         
    32         if (l1 || l2) {
    33             dummy->next = l1 ? l1 : l2;
    34         }
    35         
    36         return temp->next;
    37     }
    38 };

    由于最后是弄到list1中,但是我们不知道list1还是list2的第一个元素关系,最后结果的list1中的头结点可能会改变,所以需要引入dummy节点。

    解法二:

     1 public ListNode mergeTwoLists(ListNode l1, ListNode l2){
     2         if(l1 == null) return l2;
     3         if(l2 == null) return l1;
     4         if(l1.val < l2.val){
     5             l1.next = mergeTwoLists(l1.next, l2);
     6             return l1;
     7         } else{
     8             l2.next = mergeTwoLists(l1, l2.next);
     9             return l2;
    10         }
    11 }

    参考了@yangliguang 的代码

    解法三:

     1 public class Solution {
     2     public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
     3         if (l1 == null) return l2;
     4         if (l2 == null) return l1;
     5         
     6         ListNode handler;
     7         if(l1.val < l2.val) {
     8             handler = l1;
     9             handler.next = mergeTwoLists(l1.next, l2);
    10         } else {
    11             handler = l2;
    12             handler.next = mergeTwoLists(l1, l2.next);
    13         }
    14         
    15         return handler;
    16     }
    17 }

    参考了@RunRunCode 的代码

    解法二和解法三都是递归,还没有完全弄明白……

  • 相关阅读:
    adb实操
    android默认获取敏感权限
    Android Studio升级到3.4遇到的问题总结
    setOnTouchListener在小米手机中不走ACTION_UP而是走ACTION_CANCEL
    应用中对APK进行安装
    安卓蓝牙开发知识
    一个人开发一个产品,小程序从0到1,第9章 数组
    一个人开发一个产品,小程序从0到1,第8章 字符串
    一个人开发一个产品,小程序从0到1,第7章 数值类型
    一个人开发一个产品,小程序从0到1,第6章 常量变量
  • 原文地址:https://www.cnblogs.com/abc-begin/p/7666879.html
Copyright © 2020-2023  润新知