我的
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) { ListNode* res; if(l1==NULL){ res=l2; return res; } else if(l2==NULL){ res=l1; return res; } else if((l2->val)<(l1->val)){ res=l2; l2=l2->next; } else{ res=l1; l1=l1->next; } ListNode* ans=res; while(1){ if(l1==NULL){ res->next=l2; return ans; } else if(l2==NULL){ res->next=l1; return ans; } else if((l2->val)<(l1->val)){ res->next=l2; res=res->next; l2=l2->next; } else{ res->next=l1; res=res->next; l1=l1->next; } } return ans; } };
最快的:
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) { ListNode preHead(0), *p = &preHead; while(l1 != NULL && l2 != NULL){ if(l1->val <= l2->val){ p->next = l1; l1 = l1->next; }else{ p->next = l2; l2 = l2->next; } p = p->next; } /* while(l1 != NULL){ p->next = l1; l1 = l1->next; p = p->next; } while(l2 != NULL){ p->next = l2; l2 = l2->next; p = p->next; } */ if(l1 != NULL){ p->next = l1; } if(l2 != NULL){ p->next = l2; } return preHead.next; } };
原来是注释里的,我改成了if。和我写的一样快。都是12ms。但是原提交却是8ms……
我写得长,因为res->为NULL,没想到可以return preHead.next,学到了。