LeetCode 21. Merge Two Sorted Lists
链表并归排序
/** * 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 *ans,*p; if (l1==NULL&&l2==NULL) return NULL; else if (l1==NULL) return l2; else if (l2==NULL) return l1; if (l1->val<l2->val) { ans=new ListNode(l1->val); l1=l1->next; } else { ans=new ListNode(l2->val); l2=l2->next; } p=ans; while(l1&&l2){ if (l1->val<l2->val) { p->next=new ListNode(l1->val); l1=l1->next; } else{ p->next=new ListNode(l2->val); l2=l2->next; } p=p->next; } if (l1==NULL) (*p).next=l2; if (l2==NULL) (*p).next=l1; return ans; } };
别人的:
①设一个preHead,return preHead->next;
②直接复制地址,无需开辟新空间。
class Solution { public: ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) { ListNode phead(0); ListNode* head = &phead; while(l1 && l2){ if(l1->val < l2->val){ head->next = l1; l1 = l1->next; }else{ head->next = l2; l2 = l2->next; } head = head->next; } if(l1){ head->next = l1; } if(l2){ head->next = l2; } return phead.next; } };