首页 > 其他 > 详细

141. 环形链表

时间:2020-05-01 01:07:08      阅读:90      评论:0      收藏:0      [点我收藏+]

技术分享图片

package 链表;

/**
 * https://leetcode-cn.com/problems/linked-list-cycle/
 * 141. 环形链表
 * <p>
 * 解题思路 :采用快慢指针
 */
public class _141_Linked_List_Cycle {

    class ListNode {
        int val;
        ListNode next;

        ListNode(int x) {
            val = x;
            next = null;
        }
    }

    public class Solution {
        public boolean hasCycle(ListNode head) {
            if (head == null || head.next == null) {
                return false;
            }
            // 慢指针
            ListNode slow = head;
            // 快指针
            ListNode fast = head.next;
            while (fast != null && fast.next != null) {
                // 慢指针每次移动一个
                slow = slow.next;
                // 快指针每次移动两个
                fast = fast.next.next;
                // 如果慢指针和快指针重合说明有环
                if (slow == fast) {
                    return true;
                }
            }

            return false;
        }
    }
}

141. 环形链表

原文:https://www.cnblogs.com/jianzha/p/12812076.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!