Leetcode 141题 环形链表(Linked List Cycle) Java语言求解

题目描述:
给定一个链表,判断链表中是否有环。
为了表示给定链表中的环,我们使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。 如果 pos 是 -1,则在该链表中没有环。

Map集合解法

思路:
创建一个map集合,key为节点,value为地址值,因为ListNode没有重写toString()方法,所以用toString()方法返回的内容作为value。
如果map中存在当前节点的toString()方法返回的内容,则存在环。

/**
 * 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;
        }
        Map<ListNode,String> map = new HashMap<ListNode,String>();
        while(head != null){
            if(map.containsValue(head.toString())){
                return true;
            }
            else{
                map.put(head,head.toString());
                head = head.next;
            }
        }
        return false;
    }
}

提交结果截图:

快慢指针解法


分析:
将slow指针指向head;
将fast指针指向head.next;
在循环的过程中slow走一步,fast走两步,如果存在环,则slow和fast一定会相遇,如本例子中:slow在1处,fast在2处;然后slow走一步,到2处,fast走两步,到4处;slow到3处,fast到3处,slow和fast相遇。
代码如下:

/**
 * 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 slow = head;
        ListNode fast = head.next;
        while(fast != null){
            if(slow == fast){
                return true;
            }
            slow = slow.next;
            fast = fast.next;
            if(fast != null)
                fast = fast.next;
        }
        return false;
    }
}

对代码的解释:
1、如果head为空,则不是环,返回false;
2、如果fast不为空,则进入循环体;否则退出循环,无环,返回false;
3、如果slow和fast指向的节点相同,则存在环,返回true;
4、slow向后移动一个节点;
4、fast向后移动一个节点,如果fast不为空,再向后移动一个节点(不能直接移动两个节点,否则会报空指针异常);转2。
提交结果截图:


由图可知,快慢指针方法更好一些。

欢迎关注

扫下方二维码即可关注:
微信公众号:code随笔

posted on   随机的未知  阅读(139)  评论(0编辑  收藏  举报

编辑推荐:
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
阅读排行:
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库
· SQL Server 2025 AI相关能力初探
· 为什么 退出登录 或 修改密码 无法使 token 失效

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示