[size=medium]两个已经按照从小到大的排序的链表,合并成一个链表,仍然保持从小到大排序(貌似是归并排序里的基本操作)[/size]
#include<stdio.h>
struct Node
{
int data;
struct Node *next;
};
//创建链表
struct Node *create(int n,int count)
{
int i;
struct Node *head,*p1,*p2;
head = p1 = p2 = (struct Node*)malloc(sizeof(struct Node));
head->data = 2-n;
for(i=1; i<count; i++)
{
p1 = (struct Node*)malloc(sizeof(struct Node));
p1->data = 2*i+n;
p2->next = p1;
p2 = p1;
}
p2->next = NULL;
return head;
}
//合并链表
struct Node *merge(struct Node *p1, struct Node *p2)
{
struct Node *p,*head;
//从两个链表中确定一个头节点
if(p1->data < p2->data)
{
head = p = p1;
p1 = p1->next;
}
else
{
head = p = p2;
p2 = p2->next;
}
//合并后面的节点
while(p1 != NULL && p2 != NULL)
{
if(p1->data < p2->data)
{
p->next = p1;
p = p1;
p1 = p1->next;
}
else
{
p->next = p2;
p = p2;
p2 = p2->next;
}
}
//处理剩余的节点
if(p1 != NULL)
{
p->next = p1;
}
else
{
p->next = p2;
}
return head;
}
void main()
{
struct Node *p1,*p11,*p2,*p22,*p3;
//创建链表
p11 = p1 = create(1,5);
p22 = p2 = create(0,3);
printf("链表1初始数据:\n");
while(p1)
{
printf("%d\n", p1->data);
p1 = p1->next;
}
printf("\n链表2初始数据:\n");
while(p2)
{
printf("%d\n", p2->data);
p2 = p2->next;
}
printf("\n两个链表合并后的数据:\n");
p3 = merge(p11,p22);
while(p3)
{
printf("%d\n", p3->data);
p3 = p3->next;
}
}