论坛首页 综合技术论坛

[leetcode] LinkedListCycle

浏览 1073 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2014-10-19  
package leetcode;

/**
* <pre>
* Given a linked list, determine if it has a cycle in it.
*
* Follow up:
* Can you solve it without using extra space?
* </pre>
* */
public class LinkedListCycle {

    class ListNode {
        int      val;
        ListNode next;

        ListNode(int x) {
            val = x;
            next = null;
        }
    }

    public class Solution {
        public boolean hasCycle(ListNode head) {
            if (head == null)
                return false;
            ListNode fast = head;
            ListNode slow = head;
            while (true) {
                if (fast.next == null || fast.next.next == null)
                    return false;
                fast = fast.next.next;
                slow = slow.next;
                if (slow == fast)
                    return true;
            }
        }
    }
}
论坛首页 综合技术版

跳转论坛:
Global site tag (gtag.js) - Google Analytics