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     }
原文地址:https://www.cnblogs.com/sherry900105/p/4292330.html