两个有序链表合并为一个有序链表

#include <stdio.h>
typedef struct LNode
{
   int value;
   struct LNode *next;

}*Linklist;


Linklist phead1=(LNode*)malloc(sizeof(LNode));//链表1头

Linklist phead2=(LNode*)malloc(sizeof(LNode));//链表2头


int v1[13]={1,3,7,12,13,16,18,20,24,60,76,219,265};

int v2[7]={2,4,6,11,12,19,40};//示例


void main()
{
LNode *temp1=phead1;
LNode *temp2=phead2;
for(int i=0;i<13;i++)
{
             LNode *p=(LNode*)malloc(sizeof(LNode));

p->value=v1[i];
p->next=NULL;
temp1->next=p;
temp1=temp1->next;

}
for(int j=0;j<7;j++)
{
             LNode *q=(LNode*)malloc(sizeof(LNode));
             q->value=v2[j];
q->next=NULL;
temp2->next=q;
temp2=temp2->next;

}


LNode *cur1=phead1->next;//链表第一个元素
LNode *cur2=phead2->next;
LNode *pre1=(LNode*)malloc(sizeof(LNode));
LNode *pre2=(LNode*)malloc(sizeof(LNode));

int flag=1;


while(true)
{
while(cur1!=NULL&&cur1->value<=cur2->value)
{
pre1=cur1;
cur1=cur1->next;
}
if(cur1!=NULL)//存在1中比2小的元素
{
pre1->next=cur2;
}
else
{
flag=1;
break;
}
while(cur2!=NULL&&cur2->value<cur1->value)
{
pre2=cur2;
cur2=cur2->next;
}
if(cur2!=NULL)
{
pre2->next=cur1;
}
else
{
flag=2;
break;
}
}
if(flag==1)//cur1合并完 cur2合并到cur1后
{
pre1->next=cur2;

}
if(flag==2)
{
pre2->next=cur1;
}
while(phead1->next!=NULL)
{
printf("%d ",phead1->next->value);
phead1=phead1->next;
}
}
}
if(flag==2)
{
pre2->next=cur1;
}
while(phead1->next!=NULL)
{
printf("%d ",phead1->next->value);
phead1=phead1->next;
}
}
}
if(flag==2)
{
pre2->next=cur1;
}
while(phead1->next!=NULL)
{
printf("%d ",phead1->next->value);
phead1=phead1->next;
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值