题目:输入俩个递增排序的链表,合并这两个链表,使合并后的链表任然是有序的。
struct ListNode{
int value;
ListNode* next;
};
利用递归实现的代码如下:
1 //输入两个递增序列的链表,合并这两个链表要求输出后的链表仍然按照递增序列排序 2 #include<iostream> 3 using namespace std; 4 struct ListNode{ 5 int value; 6 ListNode *next; 7 }; 8 ListNode* merge(ListNode *phead1, ListNode* phead2)//递归屌大无比 9 { 10 if (phead1 == nullptr) 11 return phead2; 12 if (phead2 == nullptr) 13 return phead1; 14 ListNode *pMergeHead = nullptr; 15 if (phead1->value < phead2->value){ 16 pMergeHead = phead1; 17 pMergeHead->next = merge(phead1->next, phead2); 18 } 19 else{ 20 pMergeHead = phead2; 21 pMergeHead->next = merge(phead1, phead2->next); 22 } 23 return pMergeHead; 24 } 25 int main19() 26 { 27 system("pause"); 28 return 0; 29 }