LeetCode 141Linked List Cycle(判断环形链表)

Linked List Cycle
Given a linked list, determine if it has a cycle in it.
To represent a cycle in the given linked list, we use an integer pos which
represents the position (0-indexed) in the linked list where tail connects
to. If pos is -1, then there is no cycle in the linked list.
/**
 * 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||head.next==null){
            return false;
        }
        ListNode fast=head;
        ListNode slow=head;
        while(fast!=null&&fast.next!=null){//考虑有环无环的临界情况
        //无环fast.next!=null 有环fast!=null
            if(fast==slow){
                return true;
            }

            fast=fast.next.next;
            slow=slow.next;
             if(fast==slow){
             	return true;
			//有环的出口,要把这一句放到指针移动之后,不然进入循环
            //之后,二个指针都等于head,就一定会返回true,指针移动之后在判断是否相等
            //就没问题了,或者初始化的时候直接移动两个指针fast=fast.next.next
            //slow=slow.next,就没有顺序问题了
            
        }
        return false;
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值