单链表合并

某公司的面试题。

两个升序单链表a,b,给定一个节点c。不能申请其他节点情况下将a,b 按升序排列。

/
#include <iostream.h>
#include <stdio.h>
#include <stdlib.h>
 
//
//
//
struct Link
{
 int data;
 Link* next;
};
 

//
//创建链表
// nrandom: 自由因子
// nCount: 链表节点数目
 
Link* Create( const int nrandom, const int nCount )
{
  Link   *s,*r,*p; 
  int i = -1;
  p = r = new  Link;  
  p->next=NULL;     
  while( i++ < nCount )  
  {  
  s = new  Link;  
  s->data = i * nrandom + 1 ;  
  r->next = s ;  
  r = s;    
  }  
  r->next=NULL;
  r = p->next;
  while ( r->next != NULL)
  {
   cout << r->data << endl;
   r = r->next;
  }
  return  p->next; 
}
 
//


void  Combin( Link* a,Link* b, Link** h )
{
 
 if ( NULL==a && NULL==b)
 {
  cout<<"Error,there is no link!"<<endl;
 }
 //
 // a头小的情况,将a转成循环链表。b不转
 //
 if ( a->data <= b->data )
 {
  (*h)=a;
  for( ; (*h)->next!=NULL; (*h)=(*h)->next )
  {
 
  }
  (*h)->next=a;

  for(; a->data <= a->next->data; a = a->next)//a=a->next
  {
   if(b->data<a->next->data)
   {
    (*h)=b;
    b=b->next;
    (*h)->next=a->next;
    a->next=(*h);
   }   
  }
  //
  //处理后b链为空
  //
  if ( b == NULL )
  {
   (*h) = a->next;
   a->next = NULL;
  }
  else
  {
   (*h) = b;
   while ( (*h)->next != NULL ) {
    (*h) = (*h)->next;
   }
   (*h)->next = a->next;
   a->next = b;
  
   //断链操作
   while ( a->data <= a->next->data )
   {
    a = a->next;
   }
   (*h)  = a->next;
   a->next = NULL;
  }
 
 }
 //
 //b头小的情况,将b转成循环链表。a不转。
 //
 else
 {
  (*h)=b;
  for( ; (*h)->next!=NULL; (*h)=(*h)->next )
  {
 
  }
  (*h)->next=b;

  for(; b->data <= b->next->data; b = b->next)//a=a->next
  {
   if( a->data < a->next->data)
   {
    (*h) = a;
    a = a->next;
    (*h)->next = b->next;
    b->next = (*h);
   }   
  }
  //
  //
  //处理后a链为空
  if ( a == NULL )
  {
   (*h) = b->next;
   b->next = NULL;
  }
 
  else
  {
   (*h) = a;
   while ( (*h)->next != NULL ) {
    (*h) = (*h)->next;
   }
   (*h)->next = b->next;
   b->next = a;
  
   //断链操作
   while ( b->data <= b->next->data )
   {
    b = b->next;
   }
   (*h)  = b->next;
   b->next = NULL;
  }
 }
}
 
void main()
{
  Link *a, *b, *c;
  a = new Link;
  b = new Link;
  c = new Link;
  a = Create( 2, 10 );
  b = Create( 3, 20 );
  Combin(a,b,&c);

  a = c;
  while( a->next != NULL)
  {
  cout<< a->data<<endl;
  a = a->next;  
  }

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值