两个单链表是否相交

本文介绍了一种用于检测链表是否有环的算法,并在此基础上实现了交叉链表的环形检测及交叉点查找。通过创建单链表、交叉链表,以及实现环形检测函数,本文详细解释了如何判断链表是否存在环,以及如何找到两个链表的交叉点。此过程涉及指针操作、循环判断和条件分支等核心概念。

1。 判断两个链表是否有环,

如果都没有,判断最后一个节点是不是一样的。

如果一个有,一个没有,不相交。

如果都有,判断环上的一点是否在另一个单链表里。


#include <iostream>

using namespace std;

typedef struct stNode
{
	int ch;
	struct stNode *pNext;
	stNode(){ch = 0; pNext = NULL;}
}Node;

void createList( Node &head)
{
	int i = 0;
	Node *p = &head;
	
	for (; i < 10; i++)
	{
		p->pNext = new Node();
		p->pNext->ch = i;
		p = p->pNext;
	}
}

void printList( const Node &head)
{
	int i = 0;
	int times = 0;
	const Node *tmp = head.pNext;
	while (tmp)
	{
		times++;
		cout << i++ << ": " <<  tmp->ch << endl;
		if ( times  == 50)
		{
			break;
		}
		tmp = tmp->pNext;
	}
}


void createCrossList(Node &head)
{
	int i = 13;
	int crossPos = 4;
	Node *tmp;
	Node *p = &head;
	for ( ; i > 0; i--)
	{
		p->pNext = new Node();
		p->pNext->ch = i;
		if (i == crossPos)
		{
			tmp = p->pNext;
		}
		p = p->pNext;
	}

	p->pNext = tmp;
}

void desdoryCrossList(Node &head, Node &joinNode)
{
	Node *p = head.pNext;
	Node *curN = p; 
	int i = 0;
	while(curN)
	{
		if (curN == &joinNode)
		{
			i++;
			if(i == 2)
			{
				break;
			}
		}
		p = curN->pNext;
		cout << "delete " << curN->ch << endl;
		delete curN;
		curN = p;
	}
}

bool hasLoop(Node &head, Node *&a_meet, int &slowWork)
{
	Node *slow, *fast;
	slow = fast = &head;
	while (fast)
	{
		slow = slow->pNext;
		slowWork++;
		fast = fast->pNext;
		if (fast)
		{
			fast = fast->pNext;
		}
		else
		{
			return false;
		}

		if (slow == fast)
		{
			a_meet = slow;
			return true;
		}
	}
	return false;
}

Node * getJoinNode(Node &head, Node &MeetNode)
{
	Node *p1 = &head;
	Node *p2 = &MeetNode;
	while (p1 != p2)
	{
		p1 = p1->pNext;
		p2 = p2->pNext;
	}
	return p1;
}


int main()
{
	Node head ;
	head.ch = 100;
	//createList(head);
	createCrossList(head);
	int len = 0;
	Node *p = NULL;
	if (hasLoop(head, p, len))
	{
		cout << "has loop" << endl;
	}
	else
	{
		cout << "do not has loop" << endl;
	}
	//printList(head);
	cout << "The value when meeting: " << p->ch << endl;

	Node *p1 = NULL;
	int LoopLen = 0;
	hasLoop(*p, p1, LoopLen);
	cout << "loop len:" << LoopLen << endl;

	p1 = getJoinNode(head, *p);
	cout << "Join in :" << p1->ch << endl;
	desdoryCrossList(head, *p1);	
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值