CicyIris

单链表归并

#include<iostream>
using namespace std;
typedef struct linknode
{
 int data;
 struct linknode *next;
}nodetype;
nodetype *hebing(nodetype *h1,nodetype *h2)
{
 nodetype *p1=h1,*p2=h2,*t1,*t2;
 nodetype *head=(nodetype*)malloc(sizeof(nodetype));//´´½¨ÉÚ±ø
 nodetype *r=head;
 while(p1!=NULL&&p2!=NULL)
 {
  if(p1->data>p2->data)
  {
   r->next=p2;
   t2=p2->next;
   p2->next=NULL;
   p2=t2;
  }
  else if(p1->data<p2->data)
  {
   r->next=p1;t1=p1->next;p1->next=NULL;p1=t1;
  }
  else
  {
   r->next=p1;t1=p1->next;t2=p2->next;
   p1->next=NULL;p2->next=NULL;p2=t2;p1=t1;
  }
  r=r->next;
 }
 if(p1==NULL)
  r->next=p2;
 if(p2==NULL)
  r->next=p1;
 r=head;
 r=r->next;

 return r;
}

nodetype * creat()
{
 int data_put;
 nodetype *h=NULL,*s,*t;
 int i=1;
 cout<<"½¨Á¢Ò»¸öµ¥Á´±í"<<endl;
 while(1)
 {
  cout<<"ÊäÈëµÚ"<<i<<"½ÚµãµÄÊýÖµ:";
  cin>>data_put;
  if(data_put==0) break;
  if(i==1)
  {
   h=(nodetype*)malloc(sizeof(nodetype));
   h->data=data_put;h->next=NULL;t=h;
  }
  else
  {
   s=(nodetype*)malloc(sizeof(nodetype));
   s->data=data_put;s->next=NULL;t->next=s;
   t=s;
  }
  i++;
 }
 return h;
}

void disp(nodetype *h)
{
 nodetype *p=h;
 if(p==NULL) cout<<"¿Õ±í";
 while(p!=NULL)
 {cout<<p->data<<" ";p=p->next;}
 cout<<endl;
}


void main()
{
 nodetype *h1,*h2,*r;
 h1=creat();
 h2=creat();
 disp(h1);
 disp(h2);
 r=hebing(h1,h2);
 disp(r);
}

posted on 2010-10-28 11:51  CicyIris  阅读(201)  评论(0)    收藏  举报

导航