Given a linked list, determine if it has a cycle in it.
题目要求是给定一个链表,判断链表里是否有循环。有循环的链表如下图所示:
判断是否有循环,可以用到双指针思想--快慢指针。设置两个指针P_fast和P_slow,快指针的步长是2,慢指针的步长是1,如果有循环的话最终快指针和慢指针会相遇,即:P_fast==P_slow,这里在循环里,快指针不可能跳过慢指针,只要有循环,肯定会相遇,因为每次两指针的距离缩短一个单位。详细Java代码如下所示:
/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public boolean hasCycle(ListNode head) {
/***two pointers***/
ListNode p_fast=head;
ListNode p_slow=head;
while(p_fast!=null&&p_fast.next!=null)//这里的判断条件很重要
{
p_fast=p_fast.next.next;
p_slow=p_slow.next;
if(p_fast==p_slow) return true;
}
return false;
}
}
这里说一下while循环的判断条件,因为fast指针比slow指针快,所以只需要判断fast和fast.next不为空即可。