2024王道408 P39 T14

思考过程

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值