[leetcode]141. Linked List Cycle判断链表是否有环

时间:2023-12-30 10:21:14

Given a linked list, determine if it has a cycle in it.

Follow up:
Can you solve it without using extra space?

题意:

给定一个链表,判断是否循环

思路:

快慢指针

若有环,则快慢指针一定会在某个节点相遇(此处省略证明)

[leetcode]141. Linked List Cycle判断链表是否有环

代码:

 public class Solution {
public boolean hasCycle(ListNode head) {
ListNode fast = head;
ListNode slow = head;
while(fast != null && fast.next != null){
fast = fast.next.next;
slow = slow.next;
if(fast == slow) return true;
}
return false;
}
}