zoukankan      html  css  js  c++  java
  • 【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 };
  • 相关阅读:
    进程间通信(一):竞争条件与相互排斥方案
    (素材源代码) 猫猫学iOS 之UIDynamic重力、弹性碰撞吸附等现象牛逼Demo
    <html>
    模运算的规则
    ubuntu16.04重置root密码
    rancheros在vm主机部署
    基于centos7.6离线部署开k3s
    centos7.6在线yum安装docker-ce
    centos在线安装ffmpeg
    tar.bz2解压异常
  • 原文地址:https://www.cnblogs.com/Atanisi/p/8646680.html
Copyright © 2011-2022 走看看