#include<stdio.h>
#include<malloc.h>
struct ListNode {
int val;
struct ListNode *next;
};
struct ListNode*creat()
{
int x;
struct ListNode *p,*head,*r;
head=(struct ListNode*)malloc(sizeof(struct ListNode));
head->next=NULL;
scanf("%d",&x);
while(x!=0)
{
p=(struct ListNode*)malloc(sizeof(struct ListNode));
p->val=x;
p->next=head->next;
head->next=p;
scanf("%d",&x);
}
return head;
};
struct ListNode* mergeTwoLists(struct ListNode* l1, struct ListNode* l2){
struct ListNode *p1,*p2,*head,*r,*q;
head=(struct ListNode*)malloc(sizeof(struct ListNode));
head->next=NULL;
r=head;
p1=l1->next;
p2=l2->next;
if(l1==NULL)
return l2;
if(l2==NULL)
return l1;
while(p1!=NULL&&p2!=NULL)
{
if(p1->val<p2->val)
{
q=p1->next;
r->next=p1;
r=p1;
p1=q;
}
else if(p1->val>p2->val)
{
q=p2->next;
r->next=p2;
r=p2;
p2=q;
}
else
{
q=p1->next;
r->next=p1;
r=p1;
p1=q;
q=p2->next;
r->next=p2;
r=p2;
p2=q;
}
}
if(p1!=NULL)
{
r->next=p1;
p1=p1->next;
}
if(p2!=NULL)
{
r->next=p2;
p2=p2->next;
}
return head;
}
void print(struct ListNode*head)
{
struct ListNode *p;
p=head->next;
while(p!=NULL)
{
printf("%d ",p->val);
p=p->next;
}
printf("\n");
}
int main()
{
struct ListNode*l1,*l2,*l3;
printf("注意:尾插法建立链表,应从大到小输入\n");
l1=creat();
l2=creat();
printf("插入的链表为:\n");
print(l1);
print(l2);
printf("合并链表为:\n")
l3=mergeTwoLists(l1,l2);
print(l3);
return 0;
}