zoukankan      html  css  js  c++  java
  • [面试经典编程题] 1 判断链表有环与否

    题目:判断链表是否有环

    题目描述

    image-20200713203447257

    示例

    image-20200713203509333

    image-20200713203520011

    进阶:

    你能用 O(1)(即,常量)内存解决此问题吗?

    Java代码

    方法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 || head.next==null){return false;}
    
            //不是一个节点或者为空的时候,就执行快慢指针
            ListNode slow = head;
            ListNode quick = head.next;
    
            //if(head.next==head) {return true;}
            while(slow != quick){
                if(quick==null || quick.next==null) {return false;}
                slow = slow.next;
                quick = quick.next.next;
            }
            //退出while循环,即有环
            return true;
            
        }
    }
    

    方法2:哈希表

    //方法2 哈希表
        public boolean hasCycle(ListNode head) {
            //判断只有一个节点回或者无头节点的话即无环
            if(head==null || head.next==null) {return false;}
            //哈希表
            Set<ListNode> set = new HashSet<ListNode>();
            while(head!=null){
                if(set.contains(head)){
                    return true;
                }else{
                    set.add(head);
                }
                head = head.next;
            }
            return false;
        }
    }
    
  • 相关阅读:
    jmeter导出提取的值或参数化的值到excel
    超级有用的正则表达式
    性能测试监控
    asp.net 多线程
    VS代码格式化快捷键
    JS判断IE版本
    Jquery原创排序table
    将aspx转化为html代码
    Java基本语法——变量
    Entity Framework 中的LazyLoading
  • 原文地址:https://www.cnblogs.com/jiyongjia/p/13295573.html
Copyright © 2011-2022 走看看