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

leetcode练习:21. Merge Two Sorted Lists

时间:2017-10-20 16:49:12      阅读:154      评论:0      收藏:0      [点我收藏+]

标签:nbsp   code   div   head   logs   list   rip   ==   function   

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.

var mergeTwoLists = function(l1, l2) {
   var p = l1;
   var q = l2;
   var k = null;
   var head = null;
  
   if(p == null && q == null)
       return null;
   
   if(p == null )
       return q;
   if(q == null )
       return p;
    
   while(p!=null && q!=null){
       if(head == null) {
           if(p.val <= q.val) {
               head = p;
               p = p.next;
           } else {
               head = q;
               q = q.next;
           }
           k = head;
       } else {
           if(p.val <= q.val) {
               k.next = p;
               p = p.next;
           } else {
               k.next = q;
               q = q.next;
           }     
           k = k.next;
       }
       
   }
    
   if(p!=null) {
       k.next = p;
   }
    
   if(q!=null) {
       k.next = q;
   }
     
   return head;
 
    
};

 

leetcode练习:21. Merge Two Sorted Lists

标签:nbsp   code   div   head   logs   list   rip   ==   function   

原文地址:http://www.cnblogs.com/rimochiko/p/7700047.html

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