#include<stdio.h>
#include<stdlib.h>
/*实验三*/
typedef struct Node{
int num;
struct Node *next;
}node,*Linklist;
node *StartList(node *head)
{
head=(node*)malloc(sizeof(node));
head->next=NULL;
return head;
}
void insert_num(node *A,int x) /*排序函数*/
{
node *Q;
while(A->next!=NULL&&A->next->num<x)
A=A->next;
Q=(node*)malloc(sizeof(node));
Q->num=x;
Q->next=A->next;
A->next=Q;
}
Linklist link_node(Linklist pA,Linklist pB)/*合并两个单链表*/
{
Linklist a,b;
Linklist L3;
a=pA->next;
b=pB->next;
node *q;
L3=pA;
while(a->next!=NULL&&b->next!=NULL)
{
if(a->next->num<b->next->num)
{
q=a->next;
a->next=q->next;/*将结点删除*/
q->next=L3->next;
L3->next=q;
L3=L3->next;
}
else if(a->next->num>b->next->num)
{
q=b->next;
b->next=q->next;/*将结点删除*/
q->next=L3->next;
L3->next=q;
L3=L3->next;
}
}
if(a->next!=NULL){
L3->next=a->next;
a->next=NULL;
}
if(b->next!=NULL){
L3->next=b->next;
b->next=NULL;
}
return L3;
}
void print_node(node *E)
{
while(E->next!=NULL)
{
printf("%d ",E->next->num);
E=E->next;
}
}
int main()
{
node *L;
node *L1,*L2;
L1=StartList(L1);
L2=StartList(L2);
int X1,X2;
printf("输入第一个链表元素\n");
for(int L=0;L<3;L++)
{scanf("%d",&X1);
insert_num(L1,X1);
}
print_node(L1);
printf("\n");
printf("输入第二个链表元素\n");
for(int l=0;l<3;l++)
{
scanf("%d",&X2);
insert_num(L2,X2);
}
print_node(L2);
printf("\n");
printf("新链表元素为:\n");
L=link_node(L1,L2);
print_node(L);
}
![img](https://img-mid.csdnimg.cn/release/static/image/mid/ask/156092020436111.png "=600 #left")
两个递增单链表合成一个递增单链表,要求结果链表仍使用原来两个链表的空间,不另外占用其他空间。但是最后新链表只有两个元素,看看问题出在哪里,在我原有代码基础上修改
- 写回答
- 好问题 0 提建议
- 关注问题
- 邀请回答
-
3条回答 默认 最新
- CSDN专家-link 2021-10-12 14:38关注
那就已其中一个链表为基础,将另一个链表的所有节点按序插入就可以了
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 无用评论 打赏 举报