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

题目描述:一个链表中包含环,请找出该环的入口结点。
#include<iostream>
#include<set>
using namespace std;
struct ListNode
{
	int val;
	struct ListNode* next;
};
class Solution 
{
public:
    ListNode* EntryNodeOfLoop(ListNode* pHead)
	{
		set<ListNode*> str;//存储元素
		ListNode* node = pHead;
		while(node!=NULL)//遍历链表
		{
			if(str.insert(node).second)//插入元素进set,判断是否有重复的元素,没有的话执行node = node->next;
			{
				node = node->next;
			}
			else//有的话直接返回,该结点即为环的入口结点
			{
				return node;
			}
		}
	}
};


猜你喜欢

转载自blog.csdn.net/century_sunshine/article/details/80028722