本题代码如下
linklist merge(linklist* L1, linklist* L2)//将两个链表的公共元素合并产生新链表
{
lnode* ra = (*L1)->next, * rb = (*L2)->next;
lnode* r;
lnode* s;
lnode* C = (lnode*)malloc(sizeof(lnode));
C->next = NULL;
r = C;
while (ra && rb)//循环跳出条件(有一个为空就跳出)
{
if (ra->data < rb->data)//若A的当前元素较小,后移指针
ra = ra->next;
else if (ra->data > rb->data)//若B的当前元素较小,后移指针
rb = rb->data;
else//找到公共结点
{
s = (lnode*)malloc(sizeof(lnode));//创建一个结点
s->data = ra->data;//复制产生的结点*s
r->next = s;
r = s;
ra = ra->next;//A和B继续向后遍历
rb = rb->next;
}
}
r->next = NULL;//C的表尾结点置空
return C;
}
完整测试代码
#include<stdio.h>
#include<stdlib.h>
typedef struct lnode
{
int data;
struct lnode* next;
}lnode, * linklist;
int n = 5;
int a[5] = { 1,2,3,4,5 };
int b[5] = { 2,4,5,6,7 };
void buildlinklist(linklist* L, int arr[], int n)//创建链表
{
*L = (lnode*)malloc(sizeof(lnode));
(*L)->next = NULL;
lnode* s = *L, * r = *L;
int i = 0;
for (i = 0; i < n; i++)
{
s = (lnode*)malloc(sizeof(lnode));
s->data = arr[i];
s->next = r->next;
r->next = s;
r = s;
}
r->next = NULL;
}
linklist merge(linklist* L1, linklist* L2)//将两个链表的公共元素合并产生新链表
{
lnode* ra = (*L1)->next, * rb = (*L2)->next;
lnode* r;
lnode* s;
lnode* C = (lnode*)malloc(sizeof(lnode));
C->next = NULL;
r = C;
while (ra && rb)//循环跳出条件(有一个为空就跳出)
{
if (ra->data < rb->data)//若A的当前元素较小,后移指针
ra = ra->next;
else if (ra->data > rb->data)//若B的当前元素较小,后移指针
rb = rb->data;
else//找到公共结点
{
s = (lnode*)malloc(sizeof(lnode));//创建一个结点
s->data = ra->data;//复制产生的结点*s
r->next = s;
r = s;
ra = ra->next;//A和B继续向后遍历
rb = rb->next;
}
}
r->next = NULL;//C的表尾结点置空
return C;
}
void print(linklist* L)//输出单链表
{
lnode* k = (*L)->next;
while (k)
{
printf("->%d", k->data);
k = k->next;
}
}
int main()
{
linklist L1, L2;
buildlinklist(&L1, a, n);
buildlinklist(&L2, b, n);
printf("L1链表为:");
print(&L1);
printf("\nL2链表为:");
print(&L2);
linklist C = merge(&L1, &L2);
printf("\n合并后的链表为:");
print(&C);
return 0;
}