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?

    题意:

    给定一个链表,判断是否循环

    思路:

    快慢指针

    若有环,则快慢指针一定会在某个节点相遇(此处省略证明)

    代码:

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

    二刷

    思路


    If there is no cycle, the fast pointer will stop at the end of the linked list.

    If there is a cycle, the fast pointer will eventually meet with the slow pointer.

    For each iteration, the fast pointer will move one extra step. If the length of the cycle is M, after M iterations, the fast pointer will definitely move one more cycle and catch up with the slow pointer.

    public class Solution {
        public boolean hasCycle(ListNode head) {
            // corner case 
            if(head == null) return false;
            
            ListNode fast = head;
            ListNode slow = head;
            while(fast.next!= null){  /*此处遗漏了fast!=null导致报错*/
                fast = fast.next.next;
                slow = slow.next;
                if(slow == fast){
                    return true;
                }
            }
            return false;    
        }
    }
    

    这个test case表明了fast在为null的时候,就禁止进入while循环内部了,否则会导致fast.next.next没有指向。

  • 相关阅读:
    第05组 Alpha冲刺(4/4)
    第05组 Alpha冲刺(3/4)
    第05组 Alpha冲刺(2/4)
    团队作业——总结
    beta版本发布-团队
    团队作业-Beta冲刺(周五)
    团队作业-Beta冲刺(周四)
    团队作业-Beta冲刺(周三)
    个人作业——Alpha项目测试
    团队项目第四次作业
  • 原文地址:https://www.cnblogs.com/liuliu5151/p/9227172.html
Copyright © 2011-2022 走看看