其他分享
首页 > 其他分享> > 判断单链表是否有环 + 找入环的第一个结点 + 找两个链表相交的起始结点

判断单链表是否有环 + 找入环的第一个结点 + 找两个链表相交的起始结点

作者:互联网

public boolean hasCycle(ListNode head) {
        //首先判断头结点
        if(head == null){
            return false;
        }
        ListNode fast = head;
        ListNode slow = head;
        while(fast!=null && fast.next!=null){  
        //用fast来遍历链表:如果没环,fast势必会有为空的时候
        	fast = fast.next.next;
        	slow = slow.next;
        	if(fast == slow){
        		return true;
            }
        }
        return false;
}
 public ListNode detectCycle(ListNode head) {
        if(head == null){
    	    return null;
    	}
        ListNode fast = head;
        ListNode slow = head;
        while(fast!=null && fast.next!=null){
        //用fast来控制链表的遍历:如果没有环,fast势必会有为空的时候
        	fast = fast.next.next;
        	slow = slow.next;
        	if(fast == slow){
            //快慢指针相遇:有环
            //然后让一个指针从头开始走,另一个指针从相遇点开始走,两指针相遇的地方,就是环的入口
                ListNode cur = head;
                while(cur != slow){
        	        cur = cur.next;
        	        slow = slow.next;
                }
                return cur;
            }
        }
        return null;  
    }
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
       if(headA==null || headB==null){
             return null;
       }
       ListNode pA = headA;
	   ListNode pB = headB;
	   int lenA = 0;
	   int lenB = 0;
	   while(pA != null){
	        lenA++;
	        pA = pA.next;
	   }
	   while(pB != null){
	        lenB++;
	        pB = pB.next;
	   }
	   int k = Math.abs(lenA-lenB);
	   //让curA指向较长的链表
	   ListNode curA = headA;
	   ListNode curB = headB;
	   if(lenB > lenA){
	        curA = headB;
	        curB = headA;
	   }
	   //让较长的链表先走差值步,然后两个链表同时走
	   while(k>0){
	        k--;
	        curA = curA.next;
	   }
	   while(curA!=curB && curA!=null && curB!=null){
	        curA = curA.next;
	        curB = curB.next;
	   }
       //循环跳出的条件:有空或者相等
	   if(curA == curB){
	        return curA;
	   }
       else{
            return null;
       }
    }

标签:结点,slow,ListNode,fast,next,链表,有环,null
来源: https://blog.csdn.net/Darling_sheeps/article/details/120356612