剑指offer系列——16.合并两个排序的链表
Q:输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。
T:
1.我犯了个傻,没注意是两个单调递增的链表,误以为是两个无序的链表。
ListNode *Merge(ListNode *pHead1, ListNode *pHead2) {
if(pHead1 == nullptr)
return pHead2;
if(pHead2 == nullptr)
return pHead1;
vector<int> array;
while (pHead1) {
array.push_back(pHead1->val);
pHead1 = pHead1->next;
}
while (pHead2) {
array.push_back(pHead2->val);
pHead2 = pHead2->next;
}
stable_sort(array.begin(), array.end(), [](const int &a,const int &b){return a<b;});
int length = array.size();
ListNode *target = new ListNode(array[0]);
ListNode *L = target;
for (int i = 1; i < length; i++) {
ListNode *temp = new ListNode(array[i]);
target->next = temp;
target = temp;
}
return L;
}
2.常用的方法
ListNode *Merge(ListNode *pHead1, ListNode *pHead2) {
int temp = 0;
if (pHead1 == nullptr)
return pHead2;
if (pHead2 == nullptr)
return pHead1;
if (pHead1->val <= pHead2->val) {
temp = pHead1->val;
pHead1 = pHead1->next;
} else {
temp = pHead2->val;
pHead2 = pHead2->next;
}
ListNode* L = new ListNode(temp);
ListNode *list = L;
while (pHead1 && pHead2) {
if (pHead1->val <= pHead2->val) {
L->next = pHead1;
pHead1 = pHead1->next;
} else {
L->next = pHead2;
pHead2 = pHead2->next;
}
L = L->next;
}
if (pHead1 != nullptr)
L->next = pHead1;
if (pHead2 != nullptr)
L->next = pHead2;
return list;
}
3.递归
ListNode *Merge(ListNode *pHead1, ListNode *pHead2){
if (pHead1 == nullptr)
return pHead2;
if (pHead2 == nullptr)
return pHead1;
if(pHead1->val<=pHead2->val) {
pHead1->next = Merge(pHead1->next, pHead2);
return pHead1;
}
else {
pHead2->next = Merge(pHead1, pHead2->next);
return pHead2;
}
}