zoukankan      html  css  js  c++  java
  • LeetCode 141 环形链表

    LeetCode 141 环形链表

    问题描述:给定一个链表,判断链表中是否有环。
    为了表示给定链表中的环,我们使用整数pos来表示链表尾连接到链表中的位置(索引从0开始)。 如果pos -1,则在该链表中没有环。

    执行用时:0 ms, 在所有 Java 提交中击败了100.00%的用户
    内存消耗:40.1 MB, 在所有 Java 提交中击败了35.63%的用户

    public class Solution {
        public boolean hasCycle(ListNode head) {
            //边界情况:空链表、单节点无环、单节点有环
            if(head==null || head.next==null) {
                return false;
            }else if(head.next==head) {
                return true;
            }
            
            //快慢指针(p2能追上p1则存在环,且追上的位置即为表尾连接位置)
            ListNode p1 = head.next, p2 = head.next.next;
            while(p2!=null) {
                //判断相遇
                if(p1==p2) {
                    return true;
                }
                //指针移动(能前进则前进)
                if(p1!=null) {
                    p1 = p1.next;
                }
                if(p2!=null) {
                    p2 = p2.next;
                    if(p2!=null) {
                        p2 = p2.next;
                    }
                }
            }
    
            return false;
        }
    }
    
  • 相关阅读:
    mac pro发热发热发热
    从零开始搭建Vue组件库
    Charles模拟弱网测试
    webpack
    异步加载脚本
    Angular
    JavaScript模板语言
    Node.js
    gulp
    jsonp原理
  • 原文地址:https://www.cnblogs.com/CodeSPA/p/13527470.html
Copyright © 2011-2022 走看看