两个有序链表的归并!!!

 //使用递归方法编程:已经两个链表head1和head2各自有序,
//请把它们合并成一个链表依然有序。
#if 1
#include
#include
#include

typedef struct node{
 int num;
 struct node * next;
}Node;

void   creat(Node *head);
Node * merge_linklist(Node *head1, Node *head2);
void print(Node  *head);


int main(void)
{
 Node  *head, *head1, *head2;
 
 head1= (Node*)malloc(sizeof(Node));
 head2= (Node*)malloc(sizeof(Node));
 head1->next = NULL;
 head2->next = NULL;
 creat(head1);
 getchar();
 creat(head2);

 
 head = merge_linklist(head1, head2);

 printf("合并后链表为:/n");
  print(head);
 
 printf("/n") ;
 return 0;
}

void  creat(Node *head)       //head 不放数据的(数据结构书page45)
{
 Node *p = head;
 Node *s;
 int data;
 printf("建立新链表,输入非数字字符将结束输入:/n");
 
   while (1 == scanf("%d", &data))  // 尾插法
 {
  s = (Node *)malloc(sizeof(Node));
  s->num = data;
  p->next = s;
  p = s;
 }
 p->next = NULL;
}


Node * merge_linklist(Node *head1, Node *head2)
{
 Node *p, *q, *r, *head;
 p = head1->next;                         //把P = head1就错了, 为什么啊, 我的HEAD 明明是存东西的啦,吼吼
 q = head2->next ;
 head = head1;
 r = head;
 while (p != NULL && q != NULL)
 {
  if (p->num <= q->num)
  {
   r->next = p;
   r = p;
   p = p->next;
  }
  else
  {
   r->next = q;
   r = q;
   q = q->next;
  }
 }

 if (p)
 {
  r->next = p;
 }
 else
 {
  r->next = q;
 }
 free(head2);
 return head;
}

 
void print(Node  *head)
{
 Node *p = head->next ;
 
 while (p != NULL )
 {
  printf("%d/t", p->num);
  p = p->next;
 }
 
}
#endif

你可能感兴趣的:(两个有序链表的归并!!!)