【链表】Linked List Cycle

题目:

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

思路:

对于判断链表是否有环,方法很简单,用两个指针,一开始都指向头结点,一个是快指针,一次走两步,一个是慢指针,一次只走一步,当两个指针重合时表示存在环了。

fast先进入环,在slow进入之后,如果把slow看作在前面,fast在后面每次循环都向slow靠近1,所以一定会相遇,而不会出现fast直接跳过slow的情况。

/**
 * Definition for singly-linked list.
 * function ListNode(val) {
 *     this.val = val;
 *     this.next = null;
 * }
 */

/**
 * @param {ListNode} head
 * @return {boolean}
 */
var hasCycle = function(head) {
    if(head==null||head.next==null){
        return false;
    }
    
    var s=head,f=head.next.next;
    while(s!=f){
        if(f==null||f.next==null){
            return false;
        }else{
            s=s.next;
            f=f.next.next;
        }
    }
    
    return true;
};

 

posted @ 2016-01-25 10:47  很好玩  阅读(299)  评论(0编辑  收藏  举报