2024王道408 P39 T18

2024王道408 P39 T18

思考过程

  1. 首先我们需要两个指针p1和p2,分别指向h1->next和h2->next。然后看题目,要把h2链表给移到h1链表的后面,那我们肯定就要找到h1的表尾位置,因为这是循环链表所以我们也要知道h2的表尾位置。请添加图片描述
  2. 所以我们只能通过遍历h1和h2来找到表尾,就是while (p1->next != h1) {p1 = p1->next}这样不停的遍历让p1指针来到h1的表尾,p2指针也同理。现在p1和p2指针就都来到了表尾的位置。
  3. 知道了表尾的位置我们在移动就很方便了,只需要p1->next = h2->next; p2->next = h1因为是循环链表所以要把p2->next也指向h1。请添加图片描述ok大功告成so easy。

最后完整代码附上

//
// Created by 黎圣  on 2023/7/25.
//
#include "iostream"
typedef struct node
{
    int data;
    struct node *next;
}*linklist;
int a[3] = {1,2,3};
int b[3] = {4,5,6,};
int n = 3;
int m = 3;
//我举的例子

//创建循环链表h1
void CreateList1(linklist &h1)
{
    h1 = (linklist)malloc(sizeof(struct node));
    struct node *s;
    struct node *r = h1;
    for (int i = 0; i < n; i++)
    {
        s = (linklist)malloc(sizeof(struct node));
        s->data = a[i];
        r->next = s;
        r = r->next;
    }
    r->next = h1;//循环链表标志
}

//创建循环链表h2
void CreateList2(linklist &h2)
{
    h2 = (linklist)malloc(sizeof(struct node));
    struct node *s;
    struct node *r = h2;
    for (int i = 0; i < m; i++)
    {
        s = (linklist)malloc(sizeof(struct node));
        s->data = b[i];
        r->next = s;
        r = r->next;
    }
    s->next = h2;//循环链表标志
}

//打印出来方便观察
void display(linklist L)
{
    struct node *s = L->next;
    while (s != L)
    {
        printf("%d ", s->data);
        s = s->next;
    }
    printf("\n");
}

//题目源码
void add(linklist &h1, linklist &h2)
{
    struct node *p1 = h1->next;
    struct node *p2 = h2->next;
    while (p1->next != h1)
        p1 = p1->next;
    while (p2->next != h2)
        p2 = p2->next;
    p1->next = h2->next;
    p2->next = h1;
}

int main()
{
    linklist h1, h2;
    CreateList1(h1);
    CreateList2(h2);
    display(h1);
    display(h2);
    add(h1, h2);
    display(h1);
    return 0;
}

最后感谢b站up主@吸血小金鱼,思路都来自于她

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值