Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.
不申请新的节点(把两个链表的节点接起来)
提交通过:
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) { ListNode v(0),*pre = &v,*p = pre; // pre带头结点 while(l1 != NULL && l2 != NULL){ if(l1->val > l2 ->val){ p->next = l2; l2 = l2->next; p = p->next; } else{ p->next = l1; l1 = l1->next; p = p->next; } } if(l1 == NULL ) p->next = l2; else p->next = l1; return pre->next; }
------更新----------2017-11-13 20:25:13
还可以采用递归算法:
ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) { if(l1 == nullptr){ return l2; } if(l2 == nullptr){ return l1; } if(l1->val <= l2->val){ l1->next = mergeTwoLists(l1->next, l2); return l1; } else{ l2->next = mergeTwoLists(l1, l2->next); return l2; } }