zoukankan      html  css  js  c++  java
  • [leetCode]141.环形链表

    在这里插入图片描述

    哈希表

    遍历链表,将链表结点依次加入集合,如果集合中已经出现过该结点则说明是环形链表

    public class Solution {
        public boolean hasCycle(ListNode head) {
            HashSet set = new HashSet();
            while(head!=null){
                if(!set.contains(head)) set.add(head);
                else return true;
                head=head.next;
            }
            return false;
        }
    }
    

    双指针

    设置一个快指针和一个慢指针,快指针每次走两步,慢指针每次一步,想象一个圆形赛道,快指针始终会追上慢指针,如果相遇了则是环形链表,如果未相遇则快指针先到终点(fast==null 或 fast.next == null)

    public class Solution {
        public boolean hasCycle(ListNode head) {
           if (head == null || head.next == null) {
               return false;
           }
           ListNode slow = head;
           ListNode fast = head.next;//快的始终会追上慢的
           while(slow!=fast){
               if(fast == null || fast.next == null)
                    return false;
               slow = slow.next;
               fast = fast.next.next;
           }
           return true;
        }
    }
    
  • 相关阅读:
    Div+CSS 布局
    Windows Mobile 参考:
    Linux export的作用
    CSS(2)基本语法
    HTML(6)超链接
    HTML(5)常用的格式标签
    HTML(8)表格
    CSS(1) CSS简介
    HTML(7)图像、背景和颜色
    HTML(10)框架
  • 原文地址:https://www.cnblogs.com/PythonFCG/p/13860000.html
Copyright © 2011-2022 走看看