问题描述
Given a linked list, determine if it has a cycle in it.
To represent a cycle in the given linked list, we use an integer pos which represents the position (0-indexed) in the linked list where tail connects to. If pos is -1, then there is no cycle in the linked list.
思路
以用两个指针来解决这个问题。定义两个指针pfast和pslow,同时从链表的头结点pHead出发,pslow一次走一步,pfast一次走两步。
如果pfast追上了pslow(pfast == pslow),那么链表就包含环;pfast走到了链表的末尾都没有追上pslow,那么链表就不包含环。
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) {
if(head==null)
return false;
if(head.next!=null && head.next.next!=null){
ListNode pslow=head.next;
ListNode pfast=head.next.next;
while(pslow!=null && pfast!=null && pfast.next!=null){//注意判断条件写全
if(pfast==pslow)
return true;
pslow=pslow.next;
pfast=pfast.next.next;
}
}
return false;
}
}