题目:输入两个递增排序的链表,合并这两个链表并使新链表中的结点仍然是按照递增排序的。
#include <stdio.h>
#include <malloc.h>
typedef struct node
{
int value;
struct node *next;
}node,*pnode;
void create_list1(pnode *head)
{
pnode p,q;
int i;
for(i=1;i<9;i+=2)
{
if(i==1)
{
p = (pnode)malloc(sizeof(node));
if(!p)
return;
p->value = i;
p->next = NULL;
*head = p;
q = p;
}
else
{
p = (pnode)malloc(sizeof(node));
if(!p)
return;
p->value = i;
p->next = NULL;
q->next = p;
q = p;
}
}
p = *head;
printf("创建链表1为:\n");
while(p)
{
printf("%d\t",p->value);
p = p->next;
}
printf("\n");
}
void create_list2(pnode *head)
{
pnode p,q;
int i;
for(i=2;i<9;i+=2)
{
if(i==2)
{
p = (pnode)malloc(sizeof(node));
if(!p)
return;
p->value = i;
p->next = NULL;
*head = p;
q = p;
}
else
{
p = (pnode)malloc(sizeof(node));
if(!p)
return;
p->value = i;
p->next = NULL;
q->next = p;
q = p;
}
}
p = *head;
printf("创建链表2为:\n");
while(p)
{
printf("%d\t",p->value);
p = p->next;
}
printf("\n");
}
pnode merge(pnode head1, pnode head2)//迭代合并
{
if(head1==NULL && head2==NULL)//都为空指针直接返回
return NULL;
else if(head1==NULL)//head1是空指针,返回head2
return head2;
else if(head2==NULL)//head2是空指针,返回head1
return head1;
pnode merge_head,p,q,m;
p = head1;
q = head2;
if(p->value <= q->value)//确定合并后的头指针
{
merge_head = p;
p = p->next;
}
else
{
merge_head = q;
q = q->next;
}
m = merge_head;
while(p!=NULL && q!=NULL)
{
if(p->value <= q->value)
{
m->next = p;
m = p;
p = p->next;
}
else
{
m->next = q;
m = q;
q = q->next;
}
}
if(p!=NULL)//剩下的是p指针指向的链表
m->next = p;
if(q!=NULL)
m->next = q;//剩下的是q指针指向的链表
return merge_head;
}
pnode merge_recursion(pnode head1,pnode head2)//递归合并
{
if(head1==NULL && head2==NULL)
return NULL;
else if(head1==NULL)
return head2;
else if(head2==NULL)
return head1;
pnode merge_head;
if(head1->value <= head2->value)//实质就是不断的确定头指针
{
merge_head = head1;
merge_head->next = merge_recursion(head1->next,head2);
}
else
{
merge_head = head2;
merge_head->next = merge_recursion(head1,head2->next);
}
return merge_head;
}
int main()
{
pnode head1, head2,merge_head;
create_list1(&head1);
create_list2(&head2);
#if 0
merge_head = merge(head1,head2);
printf("迭代合并结果:\n");
while(merge_head!=NULL)
{
printf("%d\t",merge_head->value);
merge_head = merge_head->next;
}
printf("\n");
#endif
#if 1
merge_head = merge_recursion(head1,head2);
printf("递归合并结果:\n");
while(merge_head!=NULL)
{
printf("%d\t",merge_head->value);
merge_head = merge_head->next;
}
printf("\n");
#endif
return 0;
}