思考过程
1、先创建一个L3链表来存L1和L2中共同的元素,创建p1和p2指针来遍历L1和L2链表,还需要一个指针s,如果找到相同的元素时就要给s开辟一个空间变成结点来存放L1L2共同的元素,最后还需要一个指针s来指向L3。
2、判断p1指向的值和p2指向的值是否相等
while循环
如果p1的值小的话就移动p1的指针到下一个位置,如果p2的值小的话就移动p2的指针到下 一个位置。
如果p1和p2相等的话就代表这个元素就是我们要找的值:
给s开辟空间,s的值就等于p1或p2的值,接着用尾插法把值接入L3链表,然后让p1和p2的指针向后移。
3、最后把r的next置为空。
完整代码附上
#include "iostream"
struct node
{
int data;
struct node *next;
};
int a1[4] = {1,2,3,4};
int a2[5] = {1,4,5,7,9};
int n = 4;
int m = 5;
//以上的值都是例子
//创建链表L1
void CreateList(struct node *L1)
{
struct node *s;
struct node *r = L1;
for (int i = 0; i < n; i++)
{
s = (struct node *)malloc(sizeof(struct node));
s->data = a1[i];
r->next = s;
r = r->next;
}
s->next = NULL;
}
//创建链表L2
void CreateList2(struct node *L2)
{
struct node *s;
struct node *r = L2;
for (int i = 0; i < m; i++)
{
s = (struct node *)malloc (sizeof(struct node));
s->data = a2[i];
r->next = s;
r = r->next;
}
r->next = NULL;
}
//打印链表
void display(struct node *L)
{
struct node *s = L->next;
while (s)
{
printf("%d ", s->data);
s = s->next;
}
printf("\n");
}
struct node *L3;
//合并公共元素
void merge(struct node *L1, struct node *L2)
{
struct node *p1 = L1->next;
struct node *p2 = L2->next;
L3 = (struct node*)malloc(sizeof(struct node));
struct node *r = L3;
struct node *s;
while (p1 && p2)
{
if (p1->data < p2->data) p1 = p1->next;
else if (p1->data > p2->data) p2 = p2->next;
else
{
s = (struct node *)malloc(sizeof(struct node));
s->data = p1->data;
r->next = s;
r = s;
p1 = p1->next;
p2 = p2->next;
}
}
r->next = NULL;
}
int main()
{
struct node *L, *L2;
CreateList(L);
CreateList2(L2);
display(L);
display(L2);
merge(L, L2);
display(L3);
return 0;
}