/**
* 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 first=head;
ListNode second=head;
if(head == null || head.next == null){
return false;
}
first=first.next;
second=second.next.next;
while(first!=second && first!=null && second!=null){
first=first.next;
if(second.next == null){
return false;
}
second=second.next.next;
}
if(first == null || second == null){
return false;
}
return true;
}leetcode之Linked List Cycle
最新推荐文章于 2021-11-01 14:38:45 发布
本文介绍了一种使用快慢指针的方法来检测链表中是否存在循环的有效算法。通过两个速度不同的指针遍历链表,可以高效判断链表是否有环。

148

被折叠的 条评论
为什么被折叠?



