LeetCode 142. 环形链表 II

https://leetcode-cn.com/problems/linked-list-cycle-ii/

这个题跟今天LeetCode的每日一题是相同的思路,注意判断传入的链表是否为空以达到bug free~

/**
 * 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){
            return head;
        }
        ListNode fast = head;
        ListNode slow = head;
        while(fast.next != null && fast.next.next != null){
            fast = fast.next.next;
            slow = slow.next;
            if(fast == slow){
                fast = head;
                while(fast != slow){
                    fast = fast.next;
                    slow = slow.next;
                }
                return fast;
            }
        }
        return null;
    }
}

 

posted @ 2020-05-26 09:46  ZJPang  阅读(145)  评论(1编辑  收藏  举报