单向无头单链表的一些特殊的问题及其解决方法

//判断链表里面是否有环
int SListHasCycle(SList* plist)
{
	SListNode * fast = plist->_head;
	SListNode * slow = plist->_head;
	while (slow && fast && fast->_next)
	{
		slow = slow->_next;
		fast = fast->_next->_next;
		if (slow == fast)
		{
			return 1;
		}
		return 0;
	}
}


SList* SListGetCycle(SList* plist)//找到环,找到后直接返回结点,否则返回空
{
	SListNode * fast = plist->_head;
	SListNode * slow = plist->_head;
	while (slow && fast && fast->_next)
	{
		slow = slow->_next;
		fast = fast->_next->_next;
		if (slow == fast)
		{
			return fast;
		}
		return NULL;
	}
}

SListNode* detectCycle(SList * plist)//找到链表中的入链结点并且返回结点
{
	SListNode * tmp = SListGetCycle(plist);//找环
	if (tmp)
	{
		return NULL;
	}

//一个指针从相遇点开始跑,一个指针从起点开始跑,相等之后就找到了(相当于分叉链表的交点)
//然后返回这个结点,没找到就返回空
	SListNode * cur = plist->_head;          
	for (; cur; cur = cur->_next, tmp = tmp->_next)
	{
		if (cur == tmp)
		{
			return cur;
		}
	}
	return NULL;
}

猜你喜欢

转载自blog.csdn.net/qq_44783220/article/details/94217129