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?



CICT上有差不多的原题,

1. 初始化两个iterator都等于head, 设为a,b。

2. 每次迭代,a走一步,b走两步。

3. 如果a或者b走到null那就说明链表没有环,返回false,如果在某一步a==b则说明有环


/**
 * 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) {  
        ListNode h1 = head;
        ListNode h2 = head;
                 
        if(head == null){
            return false;
        }
                 
        while(true)
        {
            h1 = h1.next;
            h2 = h2.next;
            if( h1==null || h2 == null){
                return false;
            }else{
                h2 = h2.next;
                if(h2 == null){
                    return false;
                }
            }
                     
            if(h1 == h2){
                return true;
            }
        }
    }
}


你可能感兴趣的:(LeetCode)