c/c++单链表面试题—链表相交问题

一、判断两个单链表是否是相交
ide

思路分析:对象

最简单直接的方法就是依次遍历两条链表,判断其尾节点是否是相等,相等则相交不然不相交。it

bool CheckCross(const List& list1, const List& list2)//list1,list2为两个对象
{
	Node* l1 = list1._head;
	Node* l2 = list2._head;
	while (l1->_next)//找到list1的尾节点
	{
		l1 = l1->_next;
	}
	while (l2->_next)//找到list2的尾节点
	{
		l2 = l2->_next;
	}
	if (l1 == l2)
	{
		return true;//相交
	}
	return false;//不相交
}

二、找到两个单链表的交点ast

思路分析:class

在两个单链表长度相等的状况下是最简单的,只须要同时遍历两个链表而且不断地比较,若是相等则为交点不然不是交点。可是在两条单链表长度不相等的状况下,则能够让长度较长的链表先遍历两条链表的长度之差,而后再同时遍历既可。List

Node* GetCrossNode(List& list1, List& list2)
{
	int length1 = list1.GetListLength();//求list1的长度
	int length2 = list2.GetListLength();//求list2的长度
	int diff = 0;
	Node* slow = NULL;
	Node* fast = NULL;
	if (length1 > length2)//list1的长度比list2的长度要长
	{
		diff = length1 - length2;//单链表的长度之差
		fast = list1._head;
		slow = list2._head;
		while (diff--)
		{
			fast = fast->_next;
		}
		while (fast&&slow)
		{
			if (fast == slow)
			{
				return slow;//返回交点
			}
			fast = fast->_next;
			slow = slow->_next;
		}
	}
	else                                 //list2的长度比list1的长度要长
	{
		diff = length1 - length2;
		fast = list2._head;
		slow = list1._head;
		while (diff--)
		{
			fast = fast->_next;
		}
		while (fast&&slow)
		{
			if (fast == slow)
			{
				return slow;//返回交点
			}
			fast = fast->_next;
			slow = slow->_next;
		}
	}
	return NULL;//不相交
}

int  List::GetListLength()//求取单链表长度的方法
{
	int count = 0;
	Node* cur = _head;
	while (cur)
	{
		count++;
		cur = cur->_next;
	}
	return count;
}