《剑指offer》链表中环的入口结点

【 声明:版权所有,转载请标明出处,请勿用于商业用途。  联系信箱:[email protected]


题目链接:http://www.nowcoder.com/practice/253d2c59ec3e4bc68da16833f79a38e4?rp=3&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking


题目描述
一个链表中包含环,请找出该链表的环的入口结点。

思路
与这道题是一样的,详细解析在此:http://blog.csdn.net/libin1105/article/details/48267113


/*
struct ListNode {
    int val;
    struct ListNode *next;
    ListNode(int x) :
        val(x), next(NULL) {
    }
};
*/
class Solution
{
	public:
		ListNode* EntryNodeOfLoop(ListNode* pHead)
		{
			if(pHead==nullptr || pHead->next==nullptr)
				return nullptr;
			ListNode *first = pHead->next->next;
			ListNode *second = pHead->next;
			if(first==nullptr)
				return nullptr;
			while(first!=second)
			{
				first = first->next->next;
				second = second->next;
				if(first==nullptr || first->next==nullptr)
					return nullptr;
			}
			second = pHead;
			while(first!=second)
			{
				first = first->next;
				second = second->next;
			}
			return second;
		}
};


你可能感兴趣的:(《剑指offer》专题,《剑指offer》题目解析)