[leetcode] LinkedListCycle

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;
            }
        }
    }
}

你可能感兴趣的:(LeetCode)