• 【LeetCode】021. Merge Two Sorted Lists


    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.

    Example:

    Input: 1->2->4, 1->3->4
    Output: 1->1->2->3->4->4

    题解:

      简单的链表遍历,还可用递归做。

    Solution 1

     1 v/**
     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         ListNode dummy(-1);
    13         ListNode* cur = &dummy;
    14         
    15         while(l1 && l2) {
    16             if (l1->val < l2->val) {
    17                 cur->next = l1;
    18                 l1 = l1->next;
    19             } else {
    20                 cur->next = l2;
    21                 l2 = l2->next;
    22             }
    23             cur = cur->next;
    24         }
    25         
    26         cur->next = l1 ? l1 : l2;
    27         
    28         return dummy.next;
    29     }
    30 };

      递归方法

    Solution 2 

     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) return l2;
    13         if (!l2) return l1;
    14         
    15         if (l1->val < l2->val) {
    16             l1->next = mergeTwoLists(l1->next, l2);
    17             return l1;
    18         } else {
    19             l2->next = mergeTwoLists(l1, l2->next);
    20             return l2;
    21         }
    22     }
    23 };
  • 相关阅读:
    php 后端跨域请求
    IIS服务器文件跨域问题(几乎可以解决大多数跨域问题)
    JavaScript中的execCommand
    [原创] 利用前端+php批量生成html文件,传入新文本,输出新的html文件
    javascript 生成 uuid
    zabbix安装 检测环境 PHP bcmath off
    mysql中间件-amoeba
    MySQL备份
    ELK日志分析
    SAMBA配置文件详解
  • 原文地址:https://www.cnblogs.com/Atanisi/p/8646680.html
Copyright © 2020-2023  润新知