leetcode141环形链表

Posted lisin-lee-cooper

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode141环形链表相关的知识,希望对你有一定的参考价值。

一问题描述

1.给你一个链表的头节点 head ,判断链表中是否有环。
2.返回入环的第一个节点

二.示例代码

public class CircleNode 

    public static void main(String[] args) 

        ListNode listNode = new ListNode(1);
        ListNode listNode2 = new ListNode(2);
        ListNode listNode3 = new ListNode(3);
        ListNode listNode4 = new ListNode(4);

        listNode.next = listNode2;
        listNode2.next = listNode3;
        listNode3.next = listNode4;
        listNode4.next = listNode2;

        boolean result = circleNode(listNode);
        System.out.println(result);
        ListNode result2 = circleNode2(listNode);
        System.out.println(result2);
    

    private static boolean circleNode(ListNode head) 
        ListNode slow = head;
        ListNode fast = head;
        while (fast != null && fast.next != null) 
            fast = fast.next.next;
            slow = slow.next;
            if (fast == slow) 
                return true;
            
        
        return false;
    

    private static ListNode circleNode2(ListNode head) 
        ListNode slow = head;
        ListNode fast = head;
        while (fast != null && fast.next != null) 
            fast = fast.next.next;
            slow = slow.next;
            if (fast == slow) 
                fast = head;
                while (fast != slow) 
                    fast = fast.next;
                    slow = slow.next;
                    return fast;
                
            
        
        return null;
    

以上是关于leetcode141环形链表的主要内容,如果未能解决你的问题,请参考以下文章

leetcode 141. 环形链表

leetcode141环形链表

LeetCode第141题—环形链表—Python实现

leetcode141-环形链表

每天一道leetcode141-环形链表

leetcode-141环形链表