合并两个己排好序的链表及数组

唉,这么简单的东西,说简单是简单,关键是要把这东西写得好,老少兼知。应对所有测试用例,那就有点难了吧。
话说天下之事,作于细。
我们用图来说说吧:

    
    

看合并的步骤:
(1)
    
(2)

    
(3)

(4)

源代码:
  1. #ifndef COMBINE_TWO_LIST_H
  2. #define COMBINE_TWO_LIST_H
  3. #include"reverseList.h"
  4. ListNode *combineTwoList(ListNode *alist,ListNode *blist){
  5. if(alist==NULL&&blist!=NULL){
  6. return blist;
  7. }
  8. if(alist!=NULL&&blist==NULL){
  9. return alist;
  10. }
  11. if(alist==NULL&&blist==NULL){
  12. return NULL;
  13. }
  14. ListNode *preList=alist;
  15. ListNode *bckList=blist;
  16. ListNode *rootIndex=NULL;
  17. if(preList->val>=bckList->val){
  18. rootIndex=bckList;
  19. bckList=bckList->nxt;
  20. }else{
  21. rootIndex=preList;
  22. preList=preList->nxt;
  23. }
  24. ListNode *result=rootIndex;
  25. while(preList!=NULL&&bckList!=NULL){
  26. if(preList->val>=bckList->val){
  27. rootIndex->nxt=bckList;
  28. rootIndex=rootIndex->nxt;
  29. bckList=bckList->nxt;
  30. }else{
  31. rootIndex->nxt=preList;
  32. rootIndex=rootIndex->nxt;
  33. preList=preList->nxt;
  34. }
  35. }
  36. if(preList==NULL){
  37. rootIndex->nxt=bckList;
  38. }
  39. if(bckList==NULL){
  40. rootIndex->nxt=preList;
  41. }
  42. return result;
  43. }
  44. #endif
边界条件注意:
  1. if(preList==NULL){
  2. rootIndex->nxt=bckList;
  3. }
  4. if(bckList==NULL){
  5. rootIndex->nxt=preList;
  6. }

测试:
  1. int main(){
  2. int arr1[4]={1,3,5,7};
  3. int arr2[6]={2,4,8,8,8,10};
  4. ListNode *root1=constructList(arr1,4);
  5. ListNode *root2=constructList(arr2,6);
  6. ListNode *root=combineTwoList(root1,root2);
  7. printList(root);
  8. }

其实这种思维式和合并两个己排好的数组是差不多的,大家可能知道归并排序吧,里面不是有个合并两个己排好序的
数组的操作 吗?
嗯,我们来看看,其实也是一样。
(2)

(2)

(3)

(4)

源码:
    
  1. #ifndef COMBINE_TWO_ARR_H
  2. #define COMBINE_TWO_ARR_H
  3. int *combineArr(int *arr1,int Len1,int *arr2,int Len2){
  4. int *arr=new int[Len1+Len2];
  5. int *arr1Iter=arr1;
  6. int *arr2Iter=arr2;
  7. int *arrIter=arr;
  8. while(arr1Iter<=arr1+Len1-1&&arr2Iter<=arr2+Len2-1){
  9. if(*arr1Iter<*arr2Iter){
  10. *arrIter=*arr1Iter;
  11. arrIter++;
  12. arr1Iter++;
  13. }else{
  14. *arrIter=*arr2Iter;
  15. arrIter++;
  16. arr2Iter++;
  17. }
  18. }
  19. if(arr1Iter>arr1+Len1-1){
  20. while(arr2Iter<=arr2+Len2-1){
  21. *arrIter=*arr2Iter;
  22. arrIter++;
  23. arr2Iter++;
  24. }
  25. }
  26. if(arr2Iter>arr2+Len2-1){
  27. while(arr1Iter<=arr1+Len1-1){
  28. *arrIter=*arr1Iter;
  29. arrIter++;
  30. arr1Iter++;
  31. }
  32. }
  33. return arr;
  34. }
  35. #endif
注边界条件:
    
  1. if(arr1Iter>arr1+Len1-1){
  2. while(arr2Iter<=arr2+Len2-1){
  3. *arrIter=*arr2Iter;
  4. arrIter++;
  5. arr2Iter++;
  6. }
  7. }
  8. if(arr2Iter>arr2+Len2-1){
  9. while(arr1Iter<=arr1+Len1-1){
  10. *arrIter=*arr1Iter;
  11. arrIter++;
  12. arr1Iter++;
  13. }
  14. }

































posted @ 2015-07-24 16:03  yml435  阅读(412)  评论(0编辑  收藏  举报