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

  • 相关阅读:
    eclipse无法启动问题记录
    java环境配置
    Tomcat配置,Myeclipse破解和各种设置
    Android_Service详解及实例
    WTF
    jQuery实现图片轮播
    jQuery实现皮肤自定义
    CSS中的transform与transition
    checkbox实现全选/全不选
    ng-if可见
  • 原文地址:https://www.cnblogs.com/yrbbest/p/4438817.html
Copyright © 2011-2022 走看看