题解 | 判断链表中是否有环
import java.util.*;
/**
* 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 || head.next == null) {
return false;
}
ListNode slow = head;
ListNode fast = head.next;
while (slow!= fast) {
// 如果fast走到了空 就直接返回false
if (fast == null || fast.next == null) {
return false;
}
// slow每次都一步 fast每次走两步
slow = slow.next;
fast = fast.next.next;
}
return true;
}
}
判断链表中是否有环,使用slow和fast两个指针进行移动,slow每次移动一步,fast每次移动两步。如果有环,经过多次移动,fast一定会追上slow的。
韶音科技公司氛围 663人发布