合并两个己排好序的链表及数组
唉,这么简单的东西,说简单是简单,关键是要把这东西写得好,老少兼知。应对所有测试用例,那就有点难了吧。
![]()
看合并的步骤:![]()
![]()
其实这种思维式和合并两个己排好的数组是差不多的,大家可能知道归并排序吧,里面不是有个合并两个己排好序的![]()
![]()
![]()
![]()
话说天下之事,作于细。
我们用图来说说吧:

看合并的步骤:
(1)
![]()
![]()

(2)

(3)

(4)

源代码:
#ifndef COMBINE_TWO_LIST_H#define COMBINE_TWO_LIST_H#include"reverseList.h"ListNode *combineTwoList(ListNode *alist,ListNode *blist){if(alist==NULL&&blist!=NULL){return blist;}if(alist!=NULL&&blist==NULL){return alist;}if(alist==NULL&&blist==NULL){return NULL;}ListNode *preList=alist;ListNode *bckList=blist;ListNode *rootIndex=NULL;if(preList->val>=bckList->val){rootIndex=bckList;bckList=bckList->nxt;}else{rootIndex=preList;preList=preList->nxt;}ListNode *result=rootIndex;while(preList!=NULL&&bckList!=NULL){if(preList->val>=bckList->val){rootIndex->nxt=bckList;rootIndex=rootIndex->nxt;bckList=bckList->nxt;}else{rootIndex->nxt=preList;rootIndex=rootIndex->nxt;preList=preList->nxt;}}if(preList==NULL){rootIndex->nxt=bckList;}if(bckList==NULL){rootIndex->nxt=preList;}return result;}#endif
边界条件注意:
if(preList==NULL){rootIndex->nxt=bckList;}if(bckList==NULL){rootIndex->nxt=preList;}
测试:
int main(){int arr1[4]={1,3,5,7};int arr2[6]={2,4,8,8,8,10};ListNode *root1=constructList(arr1,4);ListNode *root2=constructList(arr2,6);ListNode *root=combineTwoList(root1,root2);printList(root);}
其实这种思维式和合并两个己排好的数组是差不多的,大家可能知道归并排序吧,里面不是有个合并两个己排好序的
数组的操作 吗?
嗯,我们来看看,其实也是一样。
(2)

(2)

(3)

(4)

源码:
#ifndef COMBINE_TWO_ARR_H#define COMBINE_TWO_ARR_Hint *combineArr(int *arr1,int Len1,int *arr2,int Len2){int *arr=new int[Len1+Len2];int *arr1Iter=arr1;int *arr2Iter=arr2;int *arrIter=arr;while(arr1Iter<=arr1+Len1-1&&arr2Iter<=arr2+Len2-1){if(*arr1Iter<*arr2Iter){*arrIter=*arr1Iter;arrIter++;arr1Iter++;}else{*arrIter=*arr2Iter;arrIter++;arr2Iter++;}}if(arr1Iter>arr1+Len1-1){while(arr2Iter<=arr2+Len2-1){*arrIter=*arr2Iter;arrIter++;arr2Iter++;}}if(arr2Iter>arr2+Len2-1){while(arr1Iter<=arr1+Len1-1){*arrIter=*arr1Iter;arrIter++;arr1Iter++;}}return arr;}#endif
注边界条件:
if(arr1Iter>arr1+Len1-1){while(arr2Iter<=arr2+Len2-1){*arrIter=*arr2Iter;arrIter++;arr2Iter++;}}if(arr2Iter>arr2+Len2-1){while(arr1Iter<=arr1+Len1-1){*arrIter=*arr1Iter;arrIter++;arr1Iter++;}}
浙公网安备 33010602011771号