题目:合并两个排序的单向链表
自己所写代码如下:
ListNode* MergeSortedLists(ListNode* pHead1, ListNode* pHead2) { if(pHead1 == NULL || pHead2 == NULL) return NULL; return (pHead1->value < pHead2->value)? MergeTwoList(pHead1,pHead2):MergeTwoList(pHead2,pHead1); } ListNode* MergeTwoList(ListNode* pFirst,ListNode* pSecond) { ListNode* pHead = pFirst; ListNode* ptemp = pSecond; while(pHead->pNext != NULL || ptemp->pNext != NULL) { while(pHead->pNext != NULL && pHead->pNext->value <= ptemp->value) pHead = pHead->pNext; ListNode* pHead1 = pHead->pNext; ListNode* ptemp1 = ptemp->pNext; ptemp->pNext = pHead->pNext; pHead->pNext = ptemp; ptemp = ptemp1; pHead = pHead1; } if(pHead->pNext == NULL) pHead->pNext = ptemp; return pFirst; }
PS:未经测试!
作者分析的太精辟了!相比之下,自己的思路还不够完善,同时没有想到用递归实现。。。
//思路:两个链表中的头结点作比较,较小的被选为‘头结点’并链接到前一节点之后; // 不断缩小规模,直到某个链表为空! //所以递归! ListNode* Merge(ListNode* pHead1, ListNode* pHead2) { //递归终止条件 //经典! if(pHead1 == NULL) return pHead2; else if(pHead2 == NULL) return pHead1; ListNode* pMerged = NULL; if(pHead1->value < pHead2->value) { pMerged = pHead1; pMerged->pNext = Merge(pHead1->pNext,pHead2); } else { pMerged = pHead2; pMerged->pNext = Merge(pHead1,pHead2->pNext); } return pMerged; }