第六周leetcode题

来源:互联网 发布:饿了么商家版for mac 编辑:程序博客网 时间:2024/05/01 22:24

description:

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.

将两个已经排好序的数组合并为一个,因为两个数列已经排好序,所以只需要分别顺序检索两个数列,将其中较小者放入新的数列中即可。注意要考虑空数列的情况。


代码如下:

class Solution {  

public:  
    ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) {  
        ListNode re(0);
        ListNode * head = &re;
          
        while(1)
        {  
            if(l1 == NULL && l2 == NULL)break; 
             
            if(l1 == NULL)
            {  
                head->next = l2;  
                l2 = l2->next;  
            }  
            else if(l2 == NULL)
            {  
                head->next = l1;  
                l1 = l1->next;  
            }  
             
              else  if(l1->val < l2->val)
              {  
                    head->next = l1;  
                    l1 = l1->next;  
                }  
              else{  
                    head->next= l2;  
                    l2 = l2->next;  
                }  
             
         
            head = head->next;  
            
            
        }  
          
        return re.next;  
    }  
};  
0 0
原创粉丝点击