合并两个有序的链表为有序链表

合并两个有序的链表为有序链表

http://blog.csdn.net/richard_rufeng/article/details/9371519

问题描述:

将两个已经排序的单向链表合并为一个链表,要求空间复杂度尽可能的小。

本题两个注意事项:

第一,任何题目都有时间和空间的要求,所以不要想当然地重建一个链表,这样会带来空间的浪费

第二,该题可以用两种方法来实现,递归和循环,在写答案之前,可以和面试官交流

具体代码如下

(i)递归方法:

[cpp] view plain copy
 
 print?
  1. struct listNode  
  2. {  
  3.   int data;  
  4.   listNode *next;  
  5. };  
  6. listNode *mergeList(listNode *p1,listNode *p2)  
  7. {  
  8.     if(p1==NULL)  
  9.     {  
  10.         return p2;  
  11.     }  
  12.     if(p2==NULL)  
  13.     {  
  14.       return p1;  
  15.     }  
  16.     listNode *next;  
  17.     if(p1->data<p2->data)  
  18.     {  
  19.         next=mergeList(p1->next,p2);  
  20.         p1->next=next;  
  21.      return p1;  
  22.     }else  
  23.     {  
  24.         next=mergeList(p1,p2->next);  
  25.         p2->next=next;  
  26.         return p2;  
  27.     }  
  28.   
  29. }  


 (ii)循环解法:

[cpp] view plain copy
 
 print?
    1. #include "stdafx.h"  
    2. #include <iostream>   
    3. #include <string>  
    4. using namespace std;  
    5. struct listNode  
    6. {  
    7.     int data;  
    8.     listNode *next;  
    9. };  
    10. listNode *mergeList(listNode *p1,listNode *p2)  
    11. {  
    12.     if(p1==NULL)  
    13.     {  
    14.         return p2;  
    15.     }  
    16.     if(p2==NULL)  
    17.     {  
    18.         return p1;  
    19.     }  
    20.     listNode *newHead,*cur;  
    21.     if(p1->data<p2->data)  
    22.     {  
    23.         newHead=p1;  
    24.         p1=p1->next;  
    25.     }else  
    26.     {  
    27.         newHead=p2;  
    28.         p2=p2->next;  
    29.     }  
    30.     cur=newHead;  
    31.     while(p1!=NULL && p2!=NULL)  
    32.     {  
    33.         if(p1->data<p2->data)  
    34.         {  
    35.             cur->next=p1;  
    36.             p1=p1->next;  
    37.             cur=cur->next;  
    38.         }else  
    39.         {  
    40.             cur->next=p2;  
    41.             p2=p2->next;  
    42.             cur=cur->next;  
    43.         }  
    44.     }  
    45.   
    46.     cur->next=p2->next==NULL?p1:p2;  
    47.     return newHead;  
    48. }  

posted on 2017-08-23 17:50  小西红柿  阅读(119)  评论(0)    收藏  举报

导航