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

Merge Two Sorted Lists--LeetCode

时间:2015-04-13 11:01:03      阅读:110      评论:0      收藏:0      [点我收藏+]

标签:c++   leetcode   算法   

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.

List* mergeTwoLists(List* l1,List* l2)
{
     List* head =NULL,*pre,*temp;
     if(l1 == NULL)
      return l2;
     if(l2 == NULL)
      return l1;
     while(l1 != NULL && l2 != NULL)
     {
         if(head ==NULL && l1->value < l2->value)
         {
            head = l1;
            pre = head;
            l1 = l1->next;
            continue;
         }   
         if(head == NULL && l1->value > l2->value)
         {
            head = l2;
            pre = head;
            l2 = l2->next;
            continue;
         }
         if(l1->value <= l2->value)
         {
            temp = l1->next;
            l1->next = pre->next;
            pre->next = l1;
            l1 = temp;
            pre = pre->next;
         }
         else
         {
            temp = l2->next;
            l2->next = pre->next;
            pre->next = l2;
            l2 = temp;
            pre = pre->next;
         }
     }
     if(l1 == NULL)
      pre->next = l2;
     if(l2 == NULL)
      pre->next = l1;
     return head;   
}


Merge Two Sorted Lists--LeetCode

标签:c++   leetcode   算法   

原文地址:http://blog.csdn.net/yusiguyuan/article/details/45022005

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