题解

linked-list-cycle-ii

http://www.nowcoder.com/questionTerminal/6e630519bf86480296d0f1c868d425ad

  1. 快慢指针找到相遇的点

  2. 从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) {
         if (head == null || head.next == null || head.next.next == null) {
             return null;
         }
    
         ListNode slow = head;
         ListNode fast = head;
         do {
             slow = slow.next;
             fast = fast.next.next;
         }
         while (fast != null && fast.next != null && slow != fast);
    
         if (fast == null || fast.next == null) {
             return null;
         }
    
         ListNode first = head;
         ListNode second = slow;
         while (first != second) {
             first = first.next;
             second = second.next;
         }
         return first;
     }
    }
全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务