代码(算法2):
/*C语言:将两个非递减的有序链表合并为一个非递增的有序链表。
结果链表仍使用原来两个链表的存储空间, 不另外占用其它的存储空间*/
/*算法2*/
#include<stdio.h>
#include<malloc.h>
typedef struct list {
int data;
struct list * next; //下一个节点地址
}list,*Linklist;
//第一条链表
Linklist L=NULL;//头
Linklist head=NULL;//首
Linklist p=NULL;
//第二条链表
Linklist L1=NULL;//头
Linklist head1=NULL;//首
Linklist p1=NULL;
//代理链表
Linklist L2=NULL;//头
Linklist q=NULL;
int main(){
int i=0,length;
printf("请输入第一个链表的长度:\n");
scanf("%d",&length);
head=(Linklist)malloc(sizeof(list));
L=head;
printf("请依次输入链表的内容:\n");
for(i;i<length;i++){
p = (Linklist)malloc(sizeof(list));
scanf("%d",&p->data);
p->next=NULL;
head->next=p;
head=p;
}
int i1=0,length1;
printf("请输入第二个链表的长度:\n");
scanf("%d",&length1);
head1=(Linklist)malloc(sizeof(list));
L1=head1;
printf("请依次输入链表的内容:\n");
for(i1;i1<length1;i1++){
p1= (Linklist)malloc(sizeof(list));
scanf("%d",&p1->data);
p1->next=NULL;
head1->next=p1;
head1=p1;
}
p=L->next;//得到首原节点
p1=L1->next;//得到首原节点
L2=(Linklist)malloc(sizeof(list));
L2=L;//指向已有链表空间
L2->next=NULL;
q=(Linklist)malloc(sizeof(list));
//循环里主要是 头插法原理
while(p||p1){
if(!p){
q=p1;
p1=p1->next;
}
else if(!p1){
q=p;
p=p->next;
}else if(p->data<=p1->data){
q=p;
p=p->next;
}else{
q=p1;
p1=p1->next;
}
q->next = L2->next;
L2->next=q;
}
free(L1);
p=L2->next;
while(p){
printf("%d ",p->data);
p=p->next;
}
}
解析图:
![](https://img-blog.csdnimg.cn/20210610195910715.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L2RhbGlhbmxpYW56dWlkYQ==,size_16,color_FFFFFF,t_70)