链表——判断链表是否有环以及环的入口结点 两个链表的节点

本文介绍了一种使用快慢指针法来判断链表中是否存在环,并通过额外遍历来找出环的大小及入口结点的方法。此算法在解决链表问题时具有高效性和简洁性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

思路:

首先,判断链表是否有环,方法为快慢指针(prear每次走两步,pfront每次走一步),若有环则总有相交的时候;

其次,找出环包含的节点数;

最后,再次遍历链表,找出环的入口结点;

 

代码如下:

 

/**
 * Definition for singly-linked list.
 * class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public ListNode detectCycle(ListNode head) {
        if(head == null||head.next == null||head.next.next == null)
            return null;
        ListNode first=head;
        ListNode second=head;
        //以后找链表中间结点用这种方法;
        while(second.next!=null&&second.next.next!=null)
            {
            second=second.next.next;
            first=first.next;
            if(first == second)
                break;
        }
        if(first!=second)
            return null;
        //环中的结点数目
        int count=1;
        while(first.next!=second)
            {
            first=first.next;
            count++;
        }
        //
        first=head;
        second=head;
        for(int i=1;i<=count;i++)
            {
            first=first.next; 
        }
        while(first!=second)
            {
            first=first.next;
            second=second.next;
        }
        return first;
    }
}

 

两个链表的第一个公共节点

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

    ListNode(int val) {
        this.val = val;
    }
}*/
public class Solution {
    public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
        if(pHead1 ==null || pHead2 == null){
            return null;
        }
        int length1=0;
        int length2=0;
        ListNode first = pHead1;
        ListNode second = pHead2;
        while(first.next != null){
            length1++;
            first=first.next;
        }
        while(second.next != null){
            length2++;
            second=second.next;
        }
        int diff = length1 - length2;
        first = pHead1;
        second = pHead2;
        if(diff < 0){
            diff = length2-length1;
            first = pHead2;
            second = pHead1;
        }
        while(diff > 0){
            first=first.next;
            diff--;
        }
        while(first.val != second.val && first.next != null){
            first=first.next;
            second=second.next;
        }
        if(first.val != second.val){
            return null;
        }
        return first;
    }
}

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值