zoukankan      html  css  js  c++  java
  • LeetCode 141 Linked List Cycle

    用快慢指针来判定是否有环。

    这里while loop里的条件,用的是fast.next != null && fast.next.next != null,保证如果没有环,slow一定在中点。

     1 public class Solution {
     2     public boolean hasCycle(ListNode head) {
     3         if (head == null || head.next == null) {
     4                 return false;
     5         }
     6         ListNode fast = head;
     7         ListNode slow = head;
     8         while (fast.next != null && fast.next.next != null) {
     9             slow = slow.next;
    10             fast = fast.next.next;
    11             if (fast == slow) {
    12                 return true;
    13             }
    14         }
    15         return false;
    16     }
    17 }
  • 相关阅读:
    SQL之层次查询
    GROUP函数
    SQL之统计
    正则表达式
    聚合函数,分析函数
    oracle函数
    Vue3.0优化
    浅谈FC
    短链接生成原理
    Vue路由传参
  • 原文地址:https://www.cnblogs.com/mayinmiao/p/8488245.html
Copyright © 2011-2022 走看看