2024王道数据结构408 P39 T18
思考过程
- 首先我们需要两个指针p1和p2,分别指向h1->next和h2->next。然后看题目,要把h2链表给移到h1链表的后面,那我们肯定就要找到h1的表尾位置,因为这是循环链表所以我们也要知道h2的表尾位置。
- 所以我们只能通过遍历h1和h2来找到表尾,就是
while (p1->next != h1) {p1 = p1->next}
这样不停的遍历让p1指针来到h1的表尾,p2指针也同理。现在p1和p2指针就都来到了表尾的位置。 - 知道了表尾的位置我们在移动就很方便了,只需要
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主@吸血小金鱼,思路都来自于她