合并两个有序的单链表

题目:有两个有序的单链表,将它们合并为一个有序的单链表,不允许分配额外空间。

分析:

        这一道题应该很简单,不分配额外空间是很容易满足的。数据结构课本上就有这样的实现,具体不多说,看参考代码:

1: struct Node 
  2: { 
  3:     int value; 
  4:     struct Node* next; 
  5: }; 
  6:  
  7: Node* mergeLinks(struct Node *head1,struct Node* head2) 
  8: { 
  9:     if(head1==NULL) 
 10:         return head2; 
 11:     if(head2==NULL) 
 12:         return head1; 
 13:  
 14:     struct Node *head; 
 15:     if(head1->value > head2->value) 
 16:     { 
 17:         head=head2; 
 18:         head2=head2->next; 
 19:     } 
 20:     else 
 21:     { 
 22:         head=head1; 
 23:         head1=head1->next; 
 24:     } 
 25:     struct Node *current=head; 
 26:     while(head1!=NULL && head2!=NULL) 
 27:     { 
 28:         if(head1->value > head2->value) 
 29:         { 
 30:             current->next=head2; 
 31:             current=head2; 
 32:             head2=head2->next; 
 33:         } 
 34:         else 
 35:         { 
 36:             current->next=head1; 
 37:             current=head1; 
 38:             head1=head1->next; 
 39:              
 40:         } 
 41:          
 42:     } 
 43:     if(head1!=NULL) 
 44:     { 
 45:         current->next=head1; 
 46:     } 
 47:     if(head2!=NULL) 
 48:     { 
 49:         current->next=head2; 
 50:     } 
 51:  
 52:     return head; 
 53:  
 54: }


  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值