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

  • 相关阅读:
    iOS 学习
    iOS 学习
    textField和textView限制输入条件
    FMDB的使用
    Xcode7以后 使用空模板
    MJPhotoBrowser BUG修复
    获得通讯录的访问权
    正则运算校验手机号码
    项目中生产模式和开发模式的切换
    自定义的进度条
  • 原文地址:https://www.cnblogs.com/yrbbest/p/4438817.html
Copyright © 2011-2022 走看看