排序两个排序的链表----递归非递归实现
ListNode* Merge1(ListNode* pHead1, ListNode* pHead2) { if(pHead1 == NULL) return pHead2; else if(pHead2 == NULL) return pHead1; ListNode* pMergedHead = NULL; if(pHead1->m_nValue < pHead2->m_nValue) { pMergedHead = pHead1; pMergedHead->m_pNext = Merge1(pHead1->m_pNext, pHead2); } else { pMergedHead = pHead2; pMergedHead->m_pNext = Merge1(pHead1, pHead2->m_pNext); } return pMergedHead; }
ListNode* Merge(ListNode* pHead1, ListNode* pHead2) { if(pHead1 == NULL) return pHead2; if(pHead2 == NULL) return pHead1; ListNode* NewHead=NULL; ListNode* temp=NULL; ListNode* pNode1 = pHead1; ListNode* pNode2 = pHead2; while(pNode1!=NULL && pNode2!=NULL) { if(NewHead==NULL) { if(pNode1->val <= pNode2->val) { NewHead =pNode1; pNode1 = pNode1->next; } else { NewHead =pNode2; pNode2 = pNode2->next; } temp=NewHead; } else { if(pNode1->val <= pNode2->val) { temp->next=pNode1; pNode1=pNode1->next; //temp->next=NULL; temp=temp->next; } else { temp->next=pNode2; pNode2=pNode2->next; //temp->next=NULL; temp=temp->next; } } } if(pNode1==NULL && pNode2!=NULL) temp->next=pNode2; else if(pNode2==NULL && pNode1!=NULL) temp->next=pNode1; return NewHead; }
积极乐观,好好coding