标签:val 链表 zha bool tno || class com 一个
package 链表;
/**
* https://leetcode-cn.com/problems/linked-list-cycle/
* 141. 环形链表
* <p>
* 解题思路 :采用快慢指针
*/
public class _141_Linked_List_Cycle {
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 (fast != null && fast.next != null) {
// 慢指针每次移动一个
slow = slow.next;
// 快指针每次移动两个
fast = fast.next.next;
// 如果慢指针和快指针重合说明有环
if (slow == fast) {
return true;
}
}
return false;
}
}
}
标签:val 链表 zha bool tno || class com 一个
原文地址:https://www.cnblogs.com/jianzha/p/12812076.html