Merge Two Sorted Lists

 1     ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) {
 2         if(l1==NULL)
 3             return l2;
 4         if(l2==NULL)
 5             return l1;
 6         ListNode *head,*p;
 7         if(l1->val<=l2->val){
 8             head=l1;
 9             l1=l1->next;
10         }
11         else{
12             head=l2;
13             l2=l2->next;
14         }
15         head->next=NULL;
16         p=head;
17         while(l1&&l2){
18             if(l1->val<=l2->val){
19                 p->next=l1;
20                 l1=l1->next;
21             }
22             else{
23                 p->next=l2;
24                 l2=l2->next;
25             }
26             p=p->next;
27             p->next=NULL;
28         }
29         while(l1){
30             p->next=l1;
31             l1=l1->next;
32             p=p->next;
33             p->next=NULL;
34         }
35         while(l2){
36             p->next=l2;
37             l2=l2->next;
38             p=p->next;
39             p->next=NULL;
40         }
41         return head;
42     }

AC

posted on 2014-03-25 11:45  crane_practice  阅读(95)  评论(0编辑  收藏  举报

导航