• Leetcode 141. 环形链表


    141. 环形链表

    题目

    给定一个链表,判断链表中是否有环。

    进阶:

    你能否不使用额外空间解决此题?

    思路

    1) 采用额外空间,使用 hashset

    2)采用快慢指针

    代码

    1. 采用 hashset
    public class Solution {
        public boolean hasCycle(ListNode head) {
                    if(head == null)
                return false;
    
            HashSet<ListNode> set = new HashSet<>();
    
            while (head!=null){
    
                if (set.contains(head)){
                    return true;
                }
                else {
                    set.add(head);
                    head = head.next;
                }
            }
            return false;
        }
    }
    1. 采用双指针

    代码

    采用双指针查找,时间性能更好

    /**
     * Definition for singly-linked list.
     * class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) {
     *         val = x;
     *         next = null;
     *     }
     * }
     */
    public class Solution {
        public boolean hasCycle(ListNode head) {
             if(head == null)
            return false;
    
            ListNode slowIndex = head;
            ListNode fastIndex =head;
    
            while (fastIndex!= null && fastIndex.next !=null){
                slowIndex = slowIndex.next;
                fastIndex =fastIndex.next.next; //如果当前节点数不足的话,最终会指向 null
    
                if (slowIndex == fastIndex){
                    return true;
                }
            }
            return false;   
        }
    }
  • 相关阅读:
    react 学习
    swiper
    日历插件
    插件 uploadify
    前端 websocket用法
    jQuery插件Highcharts
    可用于nodejs的SuperAgent(ajax API)
    git的基本命令
    自己对javascript闭包的了解
    函数中的this的四种绑定形式
  • 原文地址:https://www.cnblogs.com/HuanChen1025/p/8999272.html
Copyright © 2020-2023  润新知