🌗 141. 环形链表

吞佛童子2022年6月20日
  • algorithm
  • list
小于 1 分钟

🌗 141. 环形链表

难度: 🌗

问题描述

img_5.png


解法

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

输出

img_4.png

上次编辑于: 2022/6/20 下午8:24:47
贡献者: liuxianzhishou