ListNode* Merge(ListNode* pHead1, ListNode* pHead2)
{
if ( NULL ==pHead1 )
return pHead2;
else if ( NULL == pHead2 )
return pHead1;
ListNode* pLessHead = NULL;
ListNode* pGreaterHead = NULL;
ListNode* pRet = NULL; //注意保存"头"为了之后返回
ListNode* pNext = NULL;
if ( pHead1->val <= pHead2->val ){
pLessHead = pHead1;
pGreaterHead = pHead2;
}
else{
pLessHead = pHead2;
pGreaterHead = pHead1;
}
pRet = pLessHead;
//仔细分析逻辑就会发现,不可能运行到 pLessHead为NULL
while ( NULL != pGreaterHead ){
if ( pLessHead->val <= pGreaterHead->val ){
if ( NULL == pLessHead->next ){
pLessHead->next = pGreaterHead;
合并两个排序的链表使之依然有序(不开辟新空间在原链表上操作的非递归版本)
最新推荐文章于 2020-11-23 15:49:12 发布