题目链接

题目大意:给出一个链表,判断该链表是否有环,空间复杂度最好控制在o(1)

这个题没有给测试用例,导致没太明白题目意思,看了题解,用了两种方法示例如下:

法一(借鉴):利用两个指针,一个指针步长为2,一个指针步长为1,若链表中有环,则两个指针同时走,在某一时刻一定会走到一起;若链表中没有环,则两个指针一定会走到null,代码如下(耗时1ms):

 1     public boolean hasCycle(ListNode head) {
 2         ListNode fast = head;
 3         ListNode slow = head;
 4         while(fast != null && slow != null && fast.next != null) {
 5             slow = slow.next;
 6             fast = fast.next.next;
 7             if(slow == fast) {
 8                 return true;
 9             }
10         }
11         return false;
View Code

相关文章:

  • 2022-12-23
  • 2021-07-08
  • 2022-02-02
  • 2022-01-05
  • 2021-10-04
猜你喜欢
  • 2021-11-10
  • 2021-07-20
相关资源
相似解决方案