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.

    题目解析:

    炒鸡简单的一道题啊~但是每次都逗比。。是因为太简单了么。。

    第一次做的时候满脑子都想的是merge two sorted array那道题的思路, 第二次做的时候直接返回了head然后找了半天错误也找不出来 = = 也是醉了。。脑子不能再残一点。。

    直接新建一个node, 然后两个链表的第一个相比较, 依次把小的往新建的node后面放就好~

    注意要点:

    1. 新建两个点, 一个是head有助于最后返回, 然后另一个node = head.next;
    2. 一开始要判断, 如果有一个链表为空就可以直接返回啦~
    3. 其中一个链表走完了之后一定要把另一个链表后面剩下的加过去
    4. 返回 head.next !!!!!!!!!!!!!!!!!!!!!!
     1 public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
     2         if(l1 == null)
     3         return l2;
     4         if(l2 == null)
     5             return l1;
     6         ListNode head = new ListNode(0);
     7         ListNode cur = head;
     8         while(l1 != null && l2 != null){
     9             if(l1.val > l2.val){
    10                 cur.next = l2;
    11                 l2 = l2.next;
    12             }else{
    13                 cur.next = l1;
    14                 l1 = l1.next;
    15             }
    16             cur = cur.next;
    17         }
    18         if(l1 != null)
    19             cur.next = l1;
    20         if(l2 != null)
    21             cur.next = l2;
    22         return head.next;
    23     }
  • 相关阅读:
    BZOJ5308 ZJOI2018胖
    BZOJ5298 CQOI2018交错序列(动态规划+矩阵快速幂)
    423. Reconstruct Original Digits from English
    422. Valid Word Square
    277. Find the Celebrity
    419. Battleships in a Board
    414. Third Maximum Number
    413. Arithmetic Slices
    412. Fizz Buzz
    285. Inorder Successor in BST
  • 原文地址:https://www.cnblogs.com/sherry900105/p/4292330.html
Copyright © 2011-2022 走看看