zoukankan      html  css  js  c++  java
  • Leetcode 21. Merge Two Sorted Lists

    21. Merge Two Sorted Lists

    • Total Accepted: 138746
    • Total Submissions: 383218
    • Difficulty: 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) return l2;
    13         if(!l2) return l1;
    14         if(l1->val<l2->val){
    15             l1->next=mergeTwoLists(l1->next,l2);
    16             return l1;
    17         }
    18         l2->next=mergeTwoLists(l1,l2->next);
    19         return l2;
    20     }
    21 };

    迭代:

     1 class Solution {
     2 public:
     3     ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
     4         ListNode* head=new ListNode(-1);
     5         ListNode* end=head;
     6         while(l1&&l2){
     7             if(l1->val<l2->val){
     8                 end->next=l1;
     9                 l1=l1->next;
    10             }
    11             else{
    12                 end->next=l2;
    13                 l2=l2->next;
    14             }
    15             end=end->next;
    16         }
    17         if(l1){
    18             end->next=l1;
    19         }
    20         else{
    21             end->next=l2;
    22         }
    23         return head->next;
    24     }
    25 };
  • 相关阅读:
    RedHat/CentOS根目录扩容
    VNC安装配置
    网络命名空间
    Linux 端口信息查看
    Linux实际常用命令
    yum的配置文件介绍
    Linux下查/删/替 命令(转)
    CentOS/redhat使用光盘镜像源
    数据库的附加和分离
    Corrupted Metadata/failed to mount /sysroot
  • 原文地址:https://www.cnblogs.com/Deribs4/p/5665072.html
Copyright © 2011-2022 走看看