合并两个有序链表

#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;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值