链表的环与相交问题

 1.给定一个链表,判断链表中是否有环(定义两个引用,快慢指针,最终会相遇的)

public class Solution {
    public boolean hasCycle(ListNode head) {
        ListNode fast=head;
        ListNode slow=head;
        do{
            if(fast==null)
            {
               return false;//空链表
            }
            fast=fast.next;
            if(fast==null)
                return false;//无环链表
            slow=slow.next;
            fast=fast.next;
        }while(fast!=slow);//知道他两相等,代表相遇,即有环
       return true;
        
    }
}

2.给定一个链表,返回链表开始入环的第一个节点。 如果链表无环,则返回 null。(定义两个引用,一个从头出发,另一个从相遇点出发,同时走,相遇的第一个节点即为环的入口点) 

public class Solution {
    public ListNode detectCycle(ListNode head) {
         ListNode fast=head;
        ListNode slow=head;
        do{
            if(fast==null)
            {
               return null;//空链表
            }
            fast=fast.next;
            if(fast==null)
                return null;//无环链表
            slow=slow.next;
            fast=fast.next;
        }while(fast!=slow);//知道他两相等,代表相遇,即有环
        ListNode p=head;//p从头出发
        ListNode q=slow;//q从相遇结点出发
        while(p!=q)
        {
            p=p.next;
            q=q.next;
        }
        return p;
        
    }
}

3.求两个链表的相交结点 (分别求出两个链表的长度,定义两个引用,指向两个链表,其中一个引用先走链表之差步,然后一起走,若相等,则代表相交)

public class Solution {
    private int getLength(ListNode head){
        int len=0;
        for(ListNode cur=head;cur!=null;cur=cur.next)
        {
            len++;
        }
        return len;
    }//遍历求结点数
    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        int lena=getLength(headA);//链表a的结点数
        int lenb=getLength(headB);//链表b的结点数
        int diff=lena-lenb;//结点数差
        ListNode longer=headA;
        ListNode shorter=headB;
        if(lena<lenb)
        {
            longer=headB;
            shorter=headA;
            diff=lenb-lena;
        }
        for(int i=0;i<diff;i++)
            longer=longer.next;//结点数大的先走链表之差步。然后一起走,若相等则相交
        while(longer!=shorter)
        {
            longer=longer.next;
            shorter=shorter.next;
        }
        return longer;
    }
}
发布了40 篇原创文章 · 获赞 4 · 访问量 887

猜你喜欢

转载自blog.csdn.net/weixin_44919969/article/details/97570461