Android 笔试---C链表

(1)实现链表的逆置:可以参考http://blog.csdn.net/heyabo/article/details/7610732(有示意图)

[cpp] view plaincopy
 
  1. node *inverselinklist(node *head)  
  2.   
  3. {  
  4.         node *p1,*p2,*p3;  
  5.         if(NULL==head||NULL==head->next) {  
  6.                return head;  
  7.         }  
  8.         p1=head;  
  9.         p2=p1->next;  
  10.         while (p2) {  
  11.                p3=p2->next;  
  12.                p2->next=p1;  
  13.                p1=p2;  
  14.                p2=p3;  
  15.         }  
  16.         head->next=NULL;  
  17.         head=p1;  
  18.         return head;  
  19. }  


(2)用普通算法实现两个有序链表的合并

  

[cpp] view plaincopy
 
  1. node *mergelinklist(node *head1,node *head2)  
  2. {  
  3.     node *p1,*p2,*temp=NULL,*cur=NULL,*head=NULL;  
  4.     p1=head1;  
  5.     p2=head2;  
  6.     while (p1!=NULL&&p2!=NULL) {  
  7.   
  8.         if (p1->value<p2->value) {  
  9.             temp=p1;  
  10.             p1=p1->next;  
  11.         }  
  12.         else  
  13.         {     
  14.             temp=p2;  
  15.             p2=p2->next;  
  16.         }  
  17.         if (NULL==head) {  
  18.             cur=temp;  
  19.             head=cur;  
  20.         }  
  21.         else  
  22.         {  
  23.             cur->next=temp;  
  24.             cur=temp;     
  25.         }  
  26.       
  27.     }  
  28.     temp=(p1?p1:p2);  
  29.     while (temp!=NULL) {  
  30.             cur->next=temp;  
  31.             cur=cur->next;  
  32.             temp=temp->next;  
  33.     }  
  34.     cur->next=NULL;  
  35.     return head;  
  36. }  

 


(3)用递归算法实现两个有序列表的合并

[cpp] view plaincopy
 
  1. node *mergeRecursion(node *head1,node *head2)  
  2. {  
  3.         if(NULL==head1)  
  4.         {  
  5.                return head2;  
  6.         }  
  7.         if(NULL==head2)  
  8.         {  
  9.                return head1;  
  10.         }  
  11.         node *head=NULL;  
  12.         if (head1->value<=head2->value) {  
  13.               head=head1;  
  14.               head->next=mergeRecursion(head1->next,head2);  
  15.         }  
  16.         else  
  17.         {  
  18.                head=head2;  
  19.                head->next=mergeRecursion(head1,head2->next);  
  20.         }                
  21.         return head;  
  22. }  



(4)判断单链表中是否存在环

[cpp] view plaincopy
 
    1. bool IsExitsLoop(slist *head)  
    2. {  
    3.     slist *slow = head, *fast = head;  
    4.     while ( fast && fast->next )   
    5.     {  
    6.         slow = slow->next;  
    7.         fast = fast->next->next;  
    8.         if ( slow == fast ) break;  
    9.     }  
    10.     return !(fast == NULL || fast->next == NULL);  
    11. }  
posted @ 2014-12-24 23:56  MMLoveMeMM  阅读(235)  评论(0)    收藏  举报