zoukankan      html  css  js  c++  java
  • 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?

    链接: http://leetcode.com/problems/linked-list-cycle/

    题解:

    链表检测是否有环,使用快慢指针。

    Time Complexity - O(n), Space Complexity - O(1)。

    public class Solution {
        public boolean hasCycle(ListNode head) {
            if(head == null || head.next == null)
                return false;
            ListNode slow = head, fast = head;            
            
            while(fast != null && fast.next != null){
                fast = fast.next.next;
                slow = slow.next;
                if(slow == fast)
                    return true;
            }
            
            return false;
        }
    }

    Update:

    /**
     * Definition for singly-linked list.
     * class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) {
     *         val = x;
     *         next = null;
     *     }
     * }
     */
    public class Solution {
        public boolean hasCycle(ListNode head) {
            if(head == null || head.next == null)
                return false;
            ListNode fast = head, slow = head;
            
            while(fast != null && fast.next != null) {
                fast = fast.next.next;
                slow = slow.next;
                
                if(slow == fast)
                    return true;
            }
            
            return false;
        }
    }

    二刷:

    Java:

    /**
     * Definition for singly-linked list.
     * class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) {
     *         val = x;
     *         next = null;
     *     }
     * }
     */
    public class Solution {
        public boolean hasCycle(ListNode head) {
            if (head == null || head.next == null) return false;
            ListNode fast = head, slow = head;
            
            while (fast != null && fast.next != null) {
                fast = fast.next.next;
                slow = slow.next;
                if (fast == slow) return true;
            }
            return false;
        }
    }

    测试:

    Reference:

    http://wenku.baidu.com/view/c8f09f17376baf1ffc4fad6e.html?re=view

  • 相关阅读:
    Cheatsheet: 2010 05.25 ~ 05.31
    Cheatsheet: 2010 07.01 ~ 07.08
    Cheatsheet: 2010 07.22 ~ 07.31
    Cheatsheet: 2010 06.01 ~ 06.07
    Cheatsheet: 2010 05.11 ~ 05.17
    Cheatsheet: 2010 06.08 ~ 06.15
    Cheatsheet: 2010 06.16 ~ 06.22
    Cheatsheet: 2010 06.23 ~ 06.30
    2020.7.20第十五天
    2020.7.19第十四天
  • 原文地址:https://www.cnblogs.com/yrbbest/p/4438817.html
Copyright © 2011-2022 走看看