采用的是哈希表,加了些注释
哈希表首先要写哈希的数据结构,然后定义一个指针,然后是find和insert函数。
居然还把PTR看成了PIR,找了半天错误。= =
以下是代码:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
//哈希表
struct HashTable{
struct ListNode* key;
UT_hash_handle hh;
};
struct HashTable *hashtable;
//哈希表find
struct HashTable* find(struct ListNode* ikey){
struct HashTable* tmp;
//PTR和PIR要看清楚
HASH_FIND_PTR(hashtable, &ikey, tmp);
return tmp;
}
//哈希insert
void insert(struct ListNode* ikey){
struct HashTable* tmp = malloc(sizeof(struct HashTable));
tmp->key = ikey;
//PTR和PIR要看清楚
HASH_ADD_PTR(hashtable, key, tmp);
}
struct ListNode *detectCycle(struct ListNode *head) {
//初始化
hashtable = NULL;
//头节点不为空进行循环,遍历所有节点
while(head != NULL){
//这个IF不写,会超时
if(find(head) != NULL){
return head;
}
insert(head);
head = head ->next;
}
return false;
}
执行用时如下:
记录下自己的错误和分析,便于自己理解,也分享给大家。