zoukankan      html  css  js  c++  java
  • 判断链表是否有环(Java实现)

    判断给定的链表中是否有环。如果有环则返回true,否则返回false。

    解题思路:设置两个指针,slow和fast,fast每次走两步,slow每次走一步,如果有环的话fast一定会追上slow,判断fast==slow或者fast.next==slow即可判断

     class ListNode {
           int val;
           ListNode next;
           ListNode(int x) {
                val = x;
                next = null;
         }
     }
    
    
    public class test1 {
        public boolean hasCycle(ListNode head) {
            if(head==null || head.next==null){
                //头指针为空或者只有头节点,无环
                return false;
            }
            ListNode slow,fast = new ListNode(0);
            slow = head.next;
            fast = head.next.next;
            while(true){
                if(fast==null||fast.next==null){
                    //fast走到链表尾
                    return false;
                }else if(fast.next==slow || fast==slow){
                    return true;
                }else{
                    slow = slow.next;// slow每次走一步
                    fast = fast.next.next;//fast每次走两步
                }
            }
        }
    
        public static void main(String[] args) {
            ListNode node1 = new ListNode(1),node2 = new ListNode(2),node3 = new ListNode(3),node4=new ListNode(4);
            node1.next=node2;
            node2.next=node3;
            node3.next=node4;
            node4.next=node1;
            test1 test = new test1();
            System.out.println(test.hasCycle(node1));
        }
    }
     
    唯有热爱方能抵御岁月漫长。
  • 相关阅读:
    yum安装8.0mysql数据库
    free命令详细介绍
    linux 自定义美女欢迎界面
    shll脚本常用格式和规则使用
    liunx常用知识基本命令大全
    liunx系统二进制包安装编译mysql数据库
    CentOS7更改网卡名称
    老男孩教育100道面试题
    非关系型数据库(NoSQL)
    iptables
  • 原文地址:https://www.cnblogs.com/syq816/p/14542014.html
Copyright © 2011-2022 走看看