Merge Two Sorted Lists

1800阅读 0评论2015-03-04 qinchaowhut
分类:C/C++

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.
  1. /**
  2.  * Definition for singly-linked list.
  3.  * struct ListNode {
  4.  * int val;
  5.  * struct ListNode *next;
  6.  * };
  7.  */
struct ListNode* mergeTwoLists(struct ListNode* l1, struct ListNode* l2) {
    
     struct ListNode *h=NULL;
     struct ListNode *t=NULL;
     if(l1==NULL)
        return l2;
     else if(l2==NULL)
        return l1;
     else
     {
        while((l1!=NULL)&&(l2!=NULL))
        {
            struct ListNode *tmp=NULL;
            if(l1->val>l2->val)
            {
                tmp=l2;
                l2=l2->next;
                tmp->next=NULL;
                
            }
            else
            {
                tmp=l1;
                l1=l1->next;
                tmp->next=NULL;
                
            }
            if(h==NULL)
            {
                 h=t=tmp;
            }
            else
            {
                 t->next=tmp;
                t=tmp;
            }
        }
        if(l1==NULL)
            t->next=l2;
        else if(l1!=NULL)
            t->next=l1;
        return h;
     }
}



  1. struct ListNode *mergeTwoLists(struct ListNode *l1, struct ListNode *l2) {
  2.     if(l1==NULL)
  3.         return l2;
  4.     else if(l2==NULL)
  5.         return l1;
  6.     struct ListNode *pNode=NULL;
  7.     if(l1->val>l2->val)
  8.     {
  9.         pNode=l2;
  10.         pNode->next=mergeTwoLists(l1,l2->next);
  11.     }
  12.     else
  13.     {
  14.         pNode=l1;
  15.         pNode->next=mergeTwoLists(l1->next,l2);
  16.     }
  17.     return pNode;
  18. }

上一篇:Merge Sorted Array
下一篇:2013年个人微博推荐技术资料汇总