当前位置:   article > 正文

有两个有序的单链表,将它们合并为一个有序的单链表,不允许分配额外空间_要求实现函数,将2个带头结点的有序单链表合并为一个有序单链表,要求不增加额外的

要求实现函数,将2个带头结点的有序单链表合并为一个有序单链表,要求不增加额外的

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

分析:

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

  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: }
转自:http://xingyunbaijunwei.blog.163.com/blog/static/76538067201231943133339/
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/数据结构灵魂/article/detail/62936
推荐阅读
相关标签
  

闽ICP备14008679号