【双指针】142. 环形链表 II

142. 环形链表 II

解题思路

  • 判断是否有环 https://blog.csdn.net/qq_44653420/article/details/131720199?spm=1001.2014.3001.5501
  • 快慢指针相遇之后 然后在head处设置一个指针 相遇节点处设置一个指针
  • 两个指针每次移动一步 最后相遇 相遇就是环入口
/**
 * 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) {
    
    
        ListNode slow = head;
        ListNode fast = head;

        // 判断是否有环  
        // 快慢指针相遇之后  然后在head处设置一个指针   相遇节点处设置一个指针
        // 两个指针每次移动一步  最后相遇 相遇就是环入口
        while(fast != null && fast.next != null){
    
    
            slow= slow.next;
            fast = fast.next.next;
            if(fast == slow){
    
    
                ListNode index1 = fast;
                ListNode index2 = head;
                // 两个指针从头节点到相遇节点 每次走一步
                while(index1 != index2){
    
    
                    index1 = index1.next;
                    index2 = index2.next;
                }

                return index1;
            }
        }
        return null;

    }
}

猜你喜欢

转载自blog.csdn.net/qq_44653420/article/details/131736269