zoukankan      html  css  js  c++  java
  • LeetCode记录之21——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.

    合并两个有序的链表并将其作为新链表返回。 新链表应通过将前两个列表的节点拼接在一起。


     1 public ListNode mergeTwoLists(ListNode l1,ListNode l2){
     2         ListNode newNode;    //new一个新的节点作新的链表
     3         if (l1 == null && l2 == null) {
     4             return null;    
     5         }
     6         if (l1 == null) {    //如果L1为空,即L2长度大于L1,所以返回L2剩余节点
     7             newNode = l2;    
     8             return newNode;
     9         }
    10         if (l2 == null) {    //与上同理
    11             newNode = l1;
    12             return newNode;
    13         }
    14         if (l1.val > l2.val) {
    15             newNode = l2;
    16             l2 = l2.next;
    17         } else {
    18             newNode = l1;
    19             l1 = l1.next;
    20         }
    21         newNode.next = mergeTwoLists(l1, l2);    //采取递归思想
    22         return newNode;
    23     }
  • 相关阅读:
    处理ios键盘弹出按钮点击click失效
    vue-eahars生产编译报错
    vue页面嵌套其他页面判断是否生产https
    阿里云linux安装nginx,亲测有效
    translate函数
    html表单from练习
    html 表格标签
    selenium模块简单使用
    python字符串普通操作
    浏览器的cookie的值改成字典格式
  • 原文地址:https://www.cnblogs.com/xpang0/p/7482377.html
Copyright © 2011-2022 走看看