合并两条循环单链表

题目:有两个循环单链表,链表头指针分别为h1和h2,编写一个函数将链表h2连接到h1之后,要求连接后的链表仍保持循环链表形式。
分析:
        首先我们要找到h1的尾结点,找到尾结点后将尾结点的next指向h2的首节点,然后找到h2的尾结点,将其next指针指向h1,
        就大功告成了。

代码:

struct Link {
	int data;
	struct Link *next;
};
#include <stdlib.h>
#include <stdio.h>
void linkTwoLists(Link *h1,Link *h2) {
	struct Link *p1 = h1->next, *p2 = h2->next;
	while (p1->next != h1) p1 = p1->next;//这里要去判断p1->next是否等于h1,进而判断出是否到达尾结点
	p1->next = p2;
	while (p2->next != h2) p2 = p2->next;
	p2->next = h1;
	free(h2);//释放h2
}
int main() {
	struct Link *h1, *h2,*p;
	Link *createSinLoopLink();
	h1 = createSinLoopLink();
	h2 = createSinLoopLink();
	linkTwoLists(h1,h2);
	p = h1->next;
	while (p!=h1) {
		printf("%d ",p->data);
		p = p->next;
	}
	return 0;
}

创建循环单链表的代码如下:

#define _CRT_SECURE_NO_WARNINGS
#include <stdlib.h>
#include <stdio.h>
struct Link {
	int data;
	struct Link *next;
};
Link *createSinLoopLink() {
	int n, data;
	struct Link *head = (struct Link *)malloc(sizeof(struct Link));
	head->next = NULL;
	struct Link *p = head;
	printf("请输入节点个数:n=");
	scanf("%d", &n);
	for (int i = 0; i < n; i++) {
		printf("请输入第%d个节点值:", i + 1);
		scanf("%d", &data);
		struct Link *newP = (struct Link*)malloc(sizeof(struct Link));
		newP->data = data;
		p->next = newP;
		p = newP;
	}
	p->next = head;
	return head;
}

 一个伟大的人有两颗心:一颗心流血,一颗心宽容。

在C++中,将两个循环单链表合并通常需要创建一个新的循环链表,同时遍历这两个原有的链表,依次添加节点到新链表中。以下是合并过程的一个简单示例: ```cpp #include <iostream> // 定义单链表节点结构体 struct ListNode { int val; ListNode* next; ListNode(int x) : val(x), next(NULL) {} }; // 合并两个循环链表 ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) { // 创建新的头节点和尾指针 ListNode* head = nullptr, *tail = nullptr; if (l1 != nullptr) { head = l1; tail = l1; } else if (l2 != nullptr) { head = l2; tail = l2; } // 遍历两个链表,将较小的元素添加到新链表 while (l1 && l2) { if (l1->val <= l2->val) { tail->next = l1; l1 = l1->next; tail = tail->next; } else { tail->next = l2; l2 = l2->next; tail = tail->next; } } // 如果其中一个链表还有剩余,将其连接到新链表末尾 if (l1) { tail->next = l1; } else { tail->next = l2; } return head; // 返回新链表的头节点 } // 打印链表 void printList(ListNode* node) { while (node != nullptr) { std::cout << node->val << " -> "; node = node->next; } std::cout << "nullptr\n"; } int main() { // 例子:假设有两个循环链表l1 = [1, 2, 3] 和 l2 = [4, 5] ListNode* l1 = new ListNode(1); l1->next = new ListNode(2); l1->next->next = new ListNode(3); l1->next->next->next = l1; ListNode* l2 = new ListNode(4); l2->next = new ListNode(5); l2->next->next = l2; ListNode* mergedList = mergeTwoLists(l1, l2); printList(mergedList); return 0; } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

北街学长

你的鼓励使我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值