问题:
Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
解法1:
使用两个步伐不一样的指针遍历链表(eg:a每步走一格,b每步走两格),如果链表存在环路,两个指针总会相遇
/**
* 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) {
if(head == nullptr)
return false;
ListNode* walker = head;
ListNode* runner = head;
while(runner->next != nullptr && runner->next->next != nullptr) {
walker = walker->next;
runner = runner->next->next;
if(walker==runner) return true;
}
return false;
}
};
解法2:
过河拆桥。每走过一个节点,就将该节点的next指针置为head(相当于将已经走过的节点做标记),如果遇到某个节点的next为head,则说明之前走到过这个节点,有环路。
public class Solution {
public boolean hasCycle(ListNode head) {
ListNode p = head,pre = head;
while(p != null && p.next != null){
if (p.next == head) return true;
p = p.next;
pre.next = head;
pre = p;
}
return false;
}
}