zoukankan      html  css  js  c++  java
  • LeetCode--021--合并两个有序链表(java)

    将两个有序链表合并为一个新的有序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。 

    示例:

    输入:1->2->4, 1->3->4
    输出:1->1->2->3->4->4

    哎,这java语法忘完了,也能糊弄通过,老天真要我搞大数据开发吗???????AI我还能刚多久。。。。。。。。。。

     1 /**
     2  * Definition for singly-linked list.
     3  * public class ListNode {
     4  *     int val;
     5  *     ListNode next;
     6  *     ListNode(int x) { val = x; }
     7  * }
     8  */
     9 class Solution {
    10     public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
    11         ListNode l3 = new ListNode(-1);
    12         ListNode dummy = l3;
    13         while(l1!=null && l2 != null){
    14             if(l1.val < l2.val){
    15                 dummy.next = l1;
    16                 dummy = l1;
    17                 l1 = l1.next;
    18             }else{
    19                 dummy.next = l2;
    20                 dummy = l2;
    21                 l2 = l2.next;
    22             }
    23         }
    24         if(l1 == null){
    25             l1 = l2;
    26         }
    27         dummy.next = l1;
    28         return l3.next;
    29     }
    30 }

    官方的递归:

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

    2019-04-18 20:54:58

  • 相关阅读:
    H264关于RTP协议的实现
    RTSP交互命令简介及过程参数描述
    RTSP协议详解
    TCP 协议中MSS的理解
    RTSP 协议分析
    Linux下/etc/resolv.conf 配置DNS客户
    371. Sum of Two Integers
    python StringIO
    高效的两段式循环缓冲区──BipBuffer
    JavaScript Lib Interface (JavaScript系统定义的接口一览表)
  • 原文地址:https://www.cnblogs.com/NPC-assange/p/10732291.html
Copyright © 2011-2022 走看看