将带头结点的有序单链表A和B合并成一个新的有序表C

#include "stdafx.h"
#include "malloc.h"
typedef struct node
{
  int data;
  struct node *next;
}lnode;

void listinitiate(lnode **head)
{
   *head=(lnode *)malloc(sizeof(lnode));
   (*head)->next=NULL;
}

void listinsert(lnode *head,int n,int m)
{
   lnode *s;
   lnode *p=head;
   int i=0;
   while(i<m)
   {
        
      i++;
      p=p->next;
   }
  
   if(i==m)
   {
      s=(lnode *)malloc(sizeof(lnode));
    
      s->data=n;
      s->next=p->next;
      p->next=s;
      }
}

int listlenght(lnode *head)
{
   int i=0;
   lnode *p=head->next;
   while(p!=NULL)
   {
      p=p->next;
      i++;
   }
   return i;

}

void destroy(lnode **head)
{
   lnode *p,*p1;
   p=*head;
   while(p!=NULL)
   {
      p1=p;
      p=p->next;
      free(p1);
   }
   *head=NULL;
}

void listget(lnode *head,int n,int *x)
{
   int i=0;
   lnode *p=head->next;
 
   while(i<n)
   {
      p=p->next;
      i++;
   }

   if(i==n)
   {  
      *x=p->data;
   }
}

void bing(lnode *head1,lnode *head2)
{
   lnode *p1=head1->next;
   lnode *pre1=head1;       //p1的前一个节点
   lnode *p2=head2->next;   
   lnode *pre2=head2;        //p2的前一个节点 
   lnode *pre22=p2->next;      //p2的后一个节点
   while(p2!=NULL)
   {
       pre22=p2->next;
       while(p1!=NULL&&p2->data>p1->data)
       {
         pre1=p1;
         p1=p1->next;
        
       }
       p2->next=pre1->next;
       pre1->next=p2;
       pre2->next=pre22;
       p2=pre22;
   }
}

int main()
{
  lnode *head1,*head2;
  int i,x,k=0;

  //初始化链表head1,head2
  listinitiate(&head1);
  listinitiate(&head2);

  //插入链表head1,head2
  for(i=0;i<20;i+=2)
  {
      listinsert(head1,i,k);
      k++;
      
  }
      k=0;
  for(i=1;i<20;i+=2)
  {
      listinsert(head2,i,k);
      k++;
  }
  //显示链表head1
  for(i=0;i<listlenght(head1);i++)
  {
      listget(head1,i,&x);
      printf("%d  ",x);
  }
  //显示链表head2
  printf("\n");
  for(i=0;i<listlenght(head2);i++)
  {
      listget(head2,i,&x);
      printf("%d  ",x);
  }
  //合并链表head1,head2
  bing(head1,head2);
  printf("\n");

  //显示合并后的链表
  for(i=0;i<listlenght(head1);i++)
  {
      listget(head1,i,&x);
      printf("%d  ",x);
  }

  //释放内存
    destroy(&head1);
    destroy(&head2);
  return 1;
}

 

posted on 2013-03-05 21:21  mrheyao  阅读(612)  评论(0编辑  收藏  举报