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 };
  • 相关阅读:
    MVC概念性的内容
    类 class
    php获取真实IP地址
    面向对象static静态的属性和方法的调用
    smarty 入门2(个人总结)
    smarty入门
    读取文件内容fopen,fgets,fclose
    mysql常用命令
    mybatis查询的三种方式
    MyBatis 映射文件
  • 原文地址:https://www.cnblogs.com/Atanisi/p/8646680.html
Copyright © 2011-2022 走看看