码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode 21 Merge Two Sorted Lists

时间:2015-02-15 00:56:05      阅读:212      评论:0      收藏:0      [点我收藏+]

标签:

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     }

 

Leetcode 21 Merge Two Sorted Lists

标签:

原文地址:http://www.cnblogs.com/sherry900105/p/4292330.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!