首页 > 其他 > 详细

【链表】Linked List Cycle

时间:2016-01-25 11:22:35      阅读:184      评论:0      收藏:0      [点我收藏+]

题目:

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

 

【链表】Linked List Cycle

原文:http://www.cnblogs.com/shytong/p/5156827.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!