LeetCode(6):linked-list-cycle
2018-03-05 01:22
381 查看
题目描述
Given a linked list, determine if it has a cycle in it. Follow up: Can you solve it without using extra space?思考 看到这道题的第一眼其实是有点懵的,怎么样知道一个链表是否有环呢?显然我们不能简单地用某个指针q遍历链表,然后看是不是有q->next == NULL来判断是否有环,因为一旦有环的话,我们的指针q就出不来了,也就造成了死循环。既然如此,那我们就人为地构造一个目标让q去追逐就好了,换句话说,其实我们前面用过的快慢指针方法就可以用于判断链表是否存在环。给出代码如下:class Solution {
public:
bool hasCycle(ListNode *head) {
if(head == NULL){
return false;
}
ListNode* p = head;
ListNode* q = head;
while(q != NULL && q->next != NULL){ //q比p快的一定是一步,因为链表节点数一定能够被1整除
p = p->next;
q = q->next->next;
if(p == q){
return true;
}
}
return false;
}
}; 为什么q一定是比p快一步?难道快两步就不行么?还真不行,因为我们让q追到p时,实际上是q比p多走的部分正好等于环的长度,这个长度一定能够被1整除,但是却不一定被2整除,不能为其他数字比如3、4|也是一样的道理。 此外,这道题强调不要用额外的空间的意思是,不要用向量保存我们遇到过的节点,然后每次在里面查找看是否有一样的,如果是,则表明有环,这种方法我们这里就不给出源码了,有兴趣可以自己写一下。
Given a linked list, determine if it has a cycle in it. Follow up: Can you solve it without using extra space?思考 看到这道题的第一眼其实是有点懵的,怎么样知道一个链表是否有环呢?显然我们不能简单地用某个指针q遍历链表,然后看是不是有q->next == NULL来判断是否有环,因为一旦有环的话,我们的指针q就出不来了,也就造成了死循环。既然如此,那我们就人为地构造一个目标让q去追逐就好了,换句话说,其实我们前面用过的快慢指针方法就可以用于判断链表是否存在环。给出代码如下:class Solution {
public:
bool hasCycle(ListNode *head) {
if(head == NULL){
return false;
}
ListNode* p = head;
ListNode* q = head;
while(q != NULL && q->next != NULL){ //q比p快的一定是一步,因为链表节点数一定能够被1整除
p = p->next;
q = q->next->next;
if(p == q){
return true;
}
}
return false;
}
}; 为什么q一定是比p快一步?难道快两步就不行么?还真不行,因为我们让q追到p时,实际上是q比p多走的部分正好等于环的长度,这个长度一定能够被1整除,但是却不一定被2整除,不能为其他数字比如3、4|也是一样的道理。 此外,这道题强调不要用额外的空间的意思是,不要用向量保存我们遇到过的节点,然后每次在里面查找看是否有一样的,如果是,则表明有环,这种方法我们这里就不给出源码了,有兴趣可以自己写一下。
相关文章推荐
- [LeetCode] Linked List Cycle 单链表中的环
- LeetCode题目:Linked List Cycle II
- [LeetCode][JavaScript]Linked List Cycle II
- Linked List Cycle leetcode II java (寻找链表环的入口)
- LeetCode解题报告:Linked List Cycle && Linked List Cycle II
- leetcode(141):Linked List Cycle
- LeetCode-142 Linked List Cycle II
- leetcode142~Linked List Cycle II
- LeetCode:Linked List Cycle
- [leetcode]Linked List Cycle
- leetcode[141]Linked List Cycle
- 【LeetCode】141 Linked List Cycle (java实现)
- LeetCode Linked List Cycle II
- 【leetcode】141/142Linked List Cycle(Floyd判圈算法)
- [Leetcode] Linked List Cycle
- LeetCode Linked List Cycle II
- leetcode Linked List Cycle II
- [LeetCode]: 141: Linked List Cycle
- LeetCode_Linked List_Linked List Cycle
- LeetCode--Linked List Cycle