题目
题解
-
哈希表
visited.insert(head); -
快慢指针:快指针先行
有环必定重合
注意,无环判断,否则出错 -
关于 链表 的相关问题
缺点:无法高效获取长度,无法根据偏移快速访问元素
问题:获取倒数第k个元素,获取中间位置的元素,判断链表是否存在环,判断环的长度等和长度与位置有关的问题
双指针解决 -
删除节点考虑增加空节点
-
链表考虑递归
代码
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
// class Solution {
// public:
// bool hasCycle(ListNode *head) {
// unordered_set<ListNode*> visited;
// while(head){
// if(visited.find(head)!=visited.end())
// return true;
// visited.insert(head);
// head=head->next;
// }
// return false;
// }
// };
class Solution {
public:
bool hasCycle(ListNode *head) {
// if(head==NULL||head->next==NULL)
// return false;
ListNode *slow=head;
ListNode *fast=head;
while(fast){
fast = fast->next;//快指针先行
if(fast != nullptr) {
fast = fast->next;
}
if(fast == slow) {
return true;
}
slow = slow->next;
}
return false;
}
};