首页 > 代码库 > [LeetCode]141 Linked List Cycle

[LeetCode]141 Linked List Cycle

https://oj.leetcode.com/problems/linked-list-cycle/

http://blog.csdn.net/linhuanmars/article/details/21200601

/**
 * 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) {
        
        // Use 2 pointers.
        
        if (head == null)
            return false;
            
        ListNode one = head;
        ListNode two = head;
        while (one != null && two != null)
        {
            one = one.next;
            two = two.next;
            
            if (two != null)
                two = two.next;
                
            if (one != null && one == two)
                return true;
        }
        return false;
    }
}


[LeetCode]141 Linked List Cycle