zoukankan      html  css  js  c++  java
  • Leetcode 141 Linked List Cycle(快慢指针)

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

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

    思路解析:

    这道题是一道比较经典的面试题啊~without using extra space的解法就是使用快慢指针, 新建两个node都指向head, 其中一个每次走两格, 另一个每次走一格. 如果链表有环的话, 走的快的那个就肯定会遇到走得慢的那个(也就是转回来了~), 如果没有的话, 走得快的那个肯定就会==null.

     1 public boolean hasCycle(ListNode head) {
     2     if(head == null || head.next == null || head.next.next == null)//此处注意先判断一下~
     3         return false;
     4     ListNode fast = head;
     5     ListNode lower = head;
     6     while(fast != null && fast.next != null){
     7         fast = fast.next.next;
     8         lower = lower.next;
     9         if(fast == lower)
    10             return true;
    11     }
    12     return false;
    13 
    14 }
  • 相关阅读:
    科学计算器
    ASCII码表
    面试题(2)
    面试题(1)
    ACM/ICPC竞赛
    ACM/ICPC竞赛
    ACM-ICPC竞赛模板
    杭电题目分类(1)
    ACM/ICPC竞赛
    ACM/ICPC竞赛
  • 原文地址:https://www.cnblogs.com/sherry900105/p/4292450.html
Copyright © 2011-2022 走看看