数据结构——链表相关例题 2

1、判断两个链表是否相交

如果两个链表相交,则输出此交点的值

//构造交点
bool Makepoint(List plist1,List plist2 ,int e)
{
	Node* p = plist1->next;
	Node* s = plist2->next;//形成环的点
	Node* tail;//最后一个结点
	int a = Getlength(plist1);
	int b = Getlength(plist2);
	if (a > b)
	{
		while (a > b)
		{
			p = p->next;
			a--;
		}
	}
	else if (a < b)
	{
		while (a < b)
		{
			s = s->next;
			b--;
		}
	}
	while (p->next != NULL&&s->next!=NULL)
	{
		if (p->data == e&&s->data==e)//找到指定结点 
			s ->next=p;
		p = p->next;
		s = s->next;
	}
	return true;
}
//求两个链表的交点
Node* Point(List plist1, List plist2)
{
	assert(plist1 != NULL);
	assert(plist2 != NULL);
	if (plist1 == NULL||plist2==NULL)
		return NULL;
	Node* p = plist1->next;
	Node* q = plist2->next;
	int a = Getlength(plist1);
	int b = Getlength(plist2);
	if (a > b)
	{
		while (a > b)
		{
			p = p->next;
			a--;
		}
	}
	else if (a < b)
	{
		while (a < b)
		{
			q = q->next;
			b--;
		}
	}
	while (p != NULL && q != NULL)
	{
		if (p== q)
			return p;
		p = p->next;
		q = q->next;
	}
	return NULL;
}

测试:

int main()
{
	Node head1;
	InitList(&head1);
	for (int i = 0; i < 10; i++)
	{
		Insert_tail(&head1, i);
	}
	//Show(&head1);
	Node head2;
	InitList(&head2);
	for (int j = 0; j < 8; j++)
	{
		Insert_tail(&head2,j);
	}
	Insert(&head1, 7, 3);
	Show(&head1);
	Show(&head2);
	Makepoint(&head1, &head2, 3);
	Node*p=Point(&head1, &head2);
	if (p == NULL)
	{
		printf("两个链表没有交点!\n");
	}
	else
	{
		printf("两个链表的交点为:%d\n", p->data);
	}
	return 0;
}

运行结果:

2、输出有环链表进入环的第一个结点

//输出有环链表进入环的第一个结点
Node* IsCyclepoint(List plist)
{
	assert(plist != NULL);
	if (plist == NULL)
		return NULL;
	//设置快慢指针,一个走两步,一个走一步
	Node* p = plist->next;
	Node* q = plist->next->next;
	while (q != NULL && q->next != NULL)
	{
		if (p == q)
		{
			break;
		}
		p = p->next;
		q = q->next->next;
	}
	if (q == NULL || q->next == NULL)//无环
	{
		return NULL;
	}
	Node* s = plist;
	while (s != p)
	{
		s = s->next;
		p = p->next;
	}
	return s;
}

测试:

int main()
{
	Node head;
	InitList(&head);
	for (int i = 0; i < 20; i++)
	{
		//Insert_head(&head, i);
		Insert_tail(&head, i);
	}
	int len = Getlength(&head);
	printf("len=%d\n", len);
	Show(&head);

	//创建一个有环链表
	//IsCycle(&head);
	Node *s = Search(&head, 3);
	Node* q = Search(&head, 9);
	q->next = s;
	IsCycle(&head);
	Node* p = IsCyclepoint(&head);
	if (p == NULL)
	{
		printf("无环!\n");
	}
	else
	{
		printf("进入环的第一个结点为:%d\n", p->data);
	}
    return 0;
}

运行结果:

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

CKX源路程

你的鼓励将是我创作的最大动力

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

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

打赏作者

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

抵扣说明:

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

余额充值