题目:
Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
AC:
public class Solution {
public boolean hasCycle(ListNode head) {
ListNode fastNode = head;
ListNode slowNode = head;
while (null != fastNode && null != fastNode.next) {
slowNode = slowNode.next;
fastNode = fastNode.next.next;
if (fastNode == slowNode) {
return true;
}
}
return false;
}
}
快慢指针,如果存在圆,则快指针一定会追上慢指针。如果不存在圆,则快指针一定会走到null指针。