leetcode-141.环形链表 | LIXI.FUN
0%

leetcode-141.环形链表

题目链接

141.环形链表

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public class Solution {
public boolean hasCycle(ListNode head) {

ListNode slow = head, fast = head;

while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;

// 快慢指针相遇则意味着有环
if (slow == fast) {
return true;
}
}

// 跳出 while 则意味着没有环
return false;
}
}

复杂度分析

  • 时间复杂度: O(N)
  • 空间复杂度: O(1)
觉得有收获就鼓励下作者吧