Given a linked list, determine if it has a cycle in it.

Follow up:
Can you solve it without using extra space?

 

判断是否成环

 

1、利用set,很简单,但是题目中说不要用额外的空间。

/**
 * 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) {
        
        Set<ListNode> set = new HashSet<ListNode>();

        while( head != null ){
            if( set.contains(head) )
                return true;
            set.add(head);
            head = head.next;
        }
        return false;
        
        
    }
}

 

 

2、设置两个指针,一个每次走两个,一个每次走一个,如果走到头,那么返回false,如果相同,那么返回true。

 

/**
 * 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.next;
        ListNode slow = head;

        while( fast.next != null && fast.next.next != null ){
            slow = slow.next;
            fast = fast.next.next;
            if( fast == slow )
                return true;
        }

        return false;
        
        
    }
}