合并两个排序链表

首先,讲一下对于两个已排序链表的合并。源码如下:

首先定义链表节点node,用于保存数据data和下一个节点next:

 

[cpp]  view plain copy
  1. struct node  
  2.  
  3. int data;  
  4. struct node *next;  
  5. };  

然后对两个已排序链表进行合并,返回合并 好的链表:

 

 

[cpp]  view plain copy
  1. node *unite_sort(node *head1, node *head2)  
  2.  
  3.     node *head;  
  4.     node *cur;  
  5.       
  6.     if (NULL == head1)  
  7.      
  8.         return head2;  
  9.      
  10.     if (NULL == head2)  
  11.      
  12.         return head1;  
  13.      
  14.       
  15.     if (head1->data head2->data)//找出最小的那个data  
  16.      
  17.         head head1;  
  18.         head1 head1->next;  
  19.      
  20.     else  
  21.      
  22.         head head2;  
  23.         head2 head2->next;  
  24.      
  25.       
  26.     for (cur head; head1 != NULL && head2 != NULL;  
  27.      
  28.         if (head1->data head2->data)  
  29.          
  30.             cur->next head1;  
  31.             cur head1;  
  32.             head1 head1->next;  
  33.          
  34.         else  
  35.          
  36.             cur->next head2;  
  37.             cur head2;  
  38.             head2 head2->next;  
  39.          
  40.      
  41.       
  42.     cur->next (NULL == head1) head2 head1;//head1和head2至少有一个为空时,剩下的那个链表直接放在cur->next  
  43.       
  44.     return head;  
  45.  

若两个链表都没有进行排序,则在合并排序之前,需要对两个链表分别进行排序:

 

 

[cpp]  view plain copy
  1. void rank(struct node *node1, int count1)  
  2.  
  3.     int i,temp 0;  
  4.     struct node *_ptr;  
  5.     for (i 0;i
  6.      
  7.         for (_ptr node1->next; _ptr->next != NULL; _ptr _ptr->next)  
  8.          
  9.             if (_ptr->data _ptr->next->data)  
  10.              
  11.                 temp _ptr->data;  
  12.                 _ptr->data _ptr->next->data;  
  13.                 _ptr->next->data temp;  
  14.              
  15.          
  16.      
  17.   
  18. }  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值