• 【链表】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;
    };
  • 相关阅读:
    "Java:comp/env/"讲解与JNDI
    table的td去边框
    jsp获取所有参数
    spring-mvc设置首页
    jdbc数据库连接方式
    文件上传
    SMBMS
    过滤器和监听器
    解决Maven的JDK版本问题
    MVC
  • 原文地址:https://www.cnblogs.com/shytong/p/5156827.html
Copyright © 2020-2023  润新知