ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
//special cases?
if( !l1 && !l2 )
return NULL;
//create a header "head" , a working pointer "cur"
// caution!cannot delete any node
ListNode* head = new ListNode(0);
ListNode* cur = head ;
//cope with the common part
while( l1 && l2 )
{
if( l1->val < l2->val )
{
cur->next=l1;
//tmp = l1 ;
l1 = l1->next;
}
else
{
cur->next = l2 ;
//tmp = l2 ;
l2 = l2->next;
}
//delete tmp; cannnot delete any node
cur = cur->next;
}
//link the rest of the longer list
cur->next = l1 ? l1 : l2;
cur = head->next;
delete head;
return cur;
}
leetcode 21. Merge Two Sorted Lists
于 2019-09-30 10:47:27 首次发布