有序列表的归并

/*
发现写长代码的时候写分成小部分去实现很有必要,容易差错
*/
#include<stdio.h>
#include<stdlib.h>
struct node
{
int num;
struct node* next;

};
struct node * input(int n)
{
int i;
struct node *head,*tail,*p;
head = tail = (struct node *)malloc(sizeof(struct node));
head->next = NULL;

for(i = 0; i < n; i++)
{
p = (struct node *)malloc(sizeof(struct node));
p->next = NULL;
scanf("%d", &p->num);
tail->next = p;
tail = tail->next;
}

return head;
}

int mix(struct node *head1,struct node *head2)
{
struct node *tail,*p1,*p2;
p1 = head1->next;
p2 = head2->next;
free(head2);
tail = head1;
while(p1&&p2)
{
if(p1->num < p2->num)
{
tail->next = p1; //tail是游动指针
tail = p1; //tail徐游动,就像建立新的链表一样
p1 = p1->next;
}
else
{
tail->next = p2;
tail = p2;
p2 = p2->next;
}
}
if(p1)
{
tail->next = p1;
}
else
{
tail->next = p2;
}
p1 = head1->next;
while(p1->next != NULL)
{
printf("%d ",p1->num);
p1 = p1->next;
}
printf("%d",p1->num);
return 0;
}

int main()
{
struct node *head1,*tail,*head2,*p;
int n1,n2;

scanf("%d%d",&n1,&n2);

head1 = input(n1);
head2 = input(n2);
p = head1->next;

mix(head1,head2);
}
posted @ 2012-02-22 23:31  某某。  阅读(245)  评论(0编辑  收藏  举报