美文网首页
141. 环形链表

141. 环形链表

作者: justonemoretry | 来源:发表于2021-08-29 22:08 被阅读0次
    image.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;
            }
            // 快慢指针
            ListNode fast = head;
            ListNode slow = head;
            while (fast != null && fast.next != null) {
                fast = fast.next.next;
                slow = slow.next;
                if (fast == slow) {
                    return true;
                }
            }
            return false;
        }
    }
    

    相关文章

      网友评论

          本文标题:141. 环形链表

          本文链接:https://www.haomeiwen.com/subject/rtcpiltx.html