判断一个链表是否是环形链表,这题可以用快慢指针来解决,首先令快慢指针fastIndex、slowIndex等于head头节点,接着来一个循环 循环体是fastIndex步进两个单位slowIndex步进一个单位判断如果slowIndex等于fastIndex则是有环 因为fastIndex走的比slowIndex快所以如果链表无环那么fastIndex肯定最先遍历至链表的末尾,故循环条件是(fastIndex!=null&&fastIndex.next!=null)一定要注意的是循环体的条件一定不能颠倒我们使用短路与就会避免报空指针的错误情况(fastIndex已经为null了那么如果再执行表达式fastIndex.next就是空指针了)
/*** 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) {ListNode slowIndex = head;ListNode fastIndex = head;while (fastIndex != null&&fastIndex.next != null) {fastIndex = fastIndex.next.next;slowIndex = slowIndex.next;if (fastIndex == slowIndex)return true;}return false;}
}