题目分析;返回一个循环链表的入口
解题方案:同上一天内容一样可以采取两种方法
- 1.双指针
2.集合存储和判断
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
//这里简单的采用了集合的方法
#include<set>
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
//这里不需要对集合进行查找,所以建立无序集合来存储结点;
unordered_set<ListNode*> s;
while(head!=NULL){
//如果集合中存在结点,就会进入if执行语句中
if(s.count(head)){
//返回循环链表头节点
return head;
}
s.insert(head);
head = head->next;
}
return NULL;
}
};