23、链表是否有环、链表环的入口

1、判断链表是否有环
设置快慢指针,快指针每次走两步,慢指针每次走一步,追上就有环

class ListNode1
{
    Integer data;
    ListNode1 next=null;
    public ListNode1(Integer data)
    {
        this.data=data;
    }
}


public class testCycleNode {

    public static boolean ifHasCycle(ListNode1 head)
    {
        ListNode1 pfast=head;
        ListNode1 pslow=head;
        if(head.next==null)
            return false;
        while(pfast!=null)
        {
            pfast=pfast.next.next;
            pslow=pslow.next;
            if(pfast==pslow)
                return true;
        }
        return false;
    }
    public static void main(String[] args) {
        // 测试用例
        ListNode1 first1=new ListNode1(1);
        System.out.println(ifHasCycle(first1));
        ListNode1 first2=new ListNode1(1);
        ListNode1 second2=new ListNode1(1);
        first2.next=second2;
        second2.next=first2;
        System.out.println(ifHasCycle(first2));
        ListNode1 first3=new ListNode1(1);
        ListNode1 second3=new ListNode1(1);
        ListNode1 third3=new ListNode1(1);
        ListNode1 f3=new ListNode1(1);
        first3.next=second3;
        second3.next=third3;
        third3.next=f3;
        f3.next=second3;
        System.out.println(ifHasCycle(first3));
        ListNode1 first4=new ListNode1(1);
        ListNode1 second4=new ListNode1(1);
        ListNode1 third4=new ListNode1(1);
        ListNode1 f4=new ListNode1(1);
        first4.next=second4;
        second4.next=third4;
        third4.next=f4;
        System.out.println(ifHasCycle(first4));
    }

}

2、判断环的入口

第一步求出环的步数,即第一次快慢指针相遇的地方
第二步让一个指针从head出发,和刚才的指针一起走,再次相遇则是环的入口

/*
 public class ListNode {
    int val;
    ListNode next = null;

    ListNode(int val) {
        this.val = val;
    }
}
*/
public class Solution {

    public ListNode EntryNodeOfLoop(ListNode pHead)
    {
        if(pHead==null||pHead.next==null)return null;
        ListNode pfast=pHead;
        ListNode pslow=pHead;
        while(pfast!=null)
        {
            pfast=pfast.next.next;
            pslow=pslow.next;
            if(pfast==pslow)
            {
                pslow=pHead;
                while(pfast!=pslow)
                {
                    pfast=pfast.next;
                    pslow=pslow.next;
                }
                break;
            }
        }
        return pslow;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值