//将两个升序链表和并成一个升序序列
#include<stdio.h>
#include<stdlib.h>
typedef struct node
{
int data;
struct node *next;
}LinkNode;
LinkNode* Creat_LinkList2()
{
int x;
LinkNode* h;
LinkNode *s,*t;
printf("请输入链表的数据域的值");
scanf("%d",&x);
h=(LinkNode *)malloc (sizeof(LinkNode));
h->next=NULL;
t=h;
while(x!=-1)
{
s=(LinkNode *)malloc(sizeof(LinkNode));
s->data=x;
s->next=t->next;
t->next=s;
t=s;
scanf("%d",&x);
}
return h;
}
void PrintLink(LinkNode *h)
{
LinkNode *p;
for(p=h->next;p;p=p->next)
{
printf("%5d",p->data);
}
}
LinkNode *MergeLink(LinkNode *head1,LinkNode *head2)
{
LinkNode*p,*t,*q;
p=head1->next;
q=head2->next;
t=head1;
while(q)
{
while(p!=NULL&&p->data<q->data)
{
t=p;
p=p->next;
}
if(!p)
{
head2->next=NULL;
//这个地方要用t而不是p,切记切记,p已经为空了
t->next=q;
}
else
{
head2->next=q->next;
q->next=p;
t->next=q;
t=t->next;
}
q=head2->next;
}
return head1;
}
/*LinkNode *MergeLink(LinkNode *head1,LinkNode *head2)
{
LinkNode *p,*t;
LinkNode *h=(LinkNode *)malloc(sizeof(LinkNode));
h->next=NULL;
t=h;
while(head1->next&&head2->next)
{
if(head1->next->data<head2->next->data)
{
p=head1->next;
head1->next=p->next;
}
else
{
p=head2->next;
head2->next=p->next;
}
p->next=NULL;
t->next=p;
t=p;
}
p=head1->next!=NULL?head1->next:head2->next;
t->next=p;
t=p;
return h;
}*/
//递归适合于不带表头结点的链表
//用该方法返回的是一个不代表头节点的链表,输出的时候从第一个位置(head)开始输出
//但是以为我创建的都是带表头节点的,所以我在递归的函数中去掉了表头节点
/*LinkNode *MergeLink(LinkNode *head1,LinkNode *head2)
{
if(head1==NULL)
return head2;
if(head2==NULL)
return head1;
if(head1->data==100000)
head1=head1->next;
if(head2->data==100000)
head2=head2->next;
LinkNode *p=(LinkNode *)malloc(sizeof(LinkNode));
if(head1->data>head2->data)
{
p=head2;
p->next=MergeLink(head1,head2->next);
}
else
{
p=head1;
p->next=MergeLink(head1->next,head2);
}
return p;
}*/
int main(void)
{
LinkNode *head1,*head2,*head3;
//尾插创建链表
printf("请输入第一个升序链表\n");
head1=Creat_LinkList2();
printf("请输入第二个升序链表\n");
head2=Creat_LinkList2();
//以下两句注释在带递归方法的时候写
// head1->data=100000;
// head2->data=100000;
head3=MergeLink(head1,head2);
PrintLink(head3);
return 0;
}