天天看点

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

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

}

继续阅读