标签:
https://leetcode.com/problems/merge-two-sorted-lists/
1 /** 2 * Definition for singly-linked list. 3 * struct ListNode { 4 * int val; 5 * ListNode *next; 6 * ListNode(int x) : val(x), next(NULL) {} 7 * }; 8 */ 9 class Solution { 10 public: 11 ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) { 12 ListNode * temp; 13 ListNode * tail=NULL; 14 ListNode * res=NULL; 15 ListNode * head1=l1; 16 ListNode * head2=l2; 17 while(head1!=NULL&&head2!=NULL) 18 { 19 if(head1->val<head2->val) 20 { 21 temp=head1; 22 head1=head1->next; 23 } 24 else 25 { 26 temp=head2; 27 head2=head2->next; 28 } 29 if(res==NULL) 30 { 31 res=temp; 32 } 33 if(tail!=NULL) 34 tail->next=temp; 35 tail=temp; 36 } 37 while(head1!=NULL) 38 { 39 temp=head1; 40 head1=head1->next; 41 if(res==NULL) 42 { 43 res=temp; 44 } 45 if(tail!=NULL) 46 tail->next=temp; 47 tail=temp; 48 } 49 while(head2!=NULL) 50 { 51 temp=head2; 52 head2=head2->next; 53 if(res==NULL) 54 { 55 res=temp; 56 } 57 if(tail!=NULL) 58 tail->next=temp; 59 tail=temp; 60 } 61 return res; 62 } 63 };
标签:
原文地址:http://www.cnblogs.com/aguai1992/p/4642230.html