注意:这个cycle不一定是包含链表所有node的cycle
难点在于in place
1. 解法一:
思路:遍历所有元素,把遍历过的元素的next都改为head,如此的话,只要找到一个元素,他的next是head,就说明有cycle
public class Solution {
public boolean hasCycle(ListNode head) {
if (head == null)
return false;
ListNode temp = head.next;
ListNode runner = head;
while(runner != null){
if (runner.next == head)
return true;
temp = runner.next;
runner.next = head;
runner = temp;
}
return false;
}
}
2.解法二:
采用快慢指针,快指针一次两步,慢指针一次一步,如果快慢指针相遇,则有环