您的位置:首页 > 编程语言 > Java开发

leetcode:142. Linked List Cycle II(Java)解答

2015-12-27 16:36 471 查看
转载请注明出处:z_zhaojun的博客

原文地址:/article/3591780.html

题目地址:https://leetcode.com/problems/linked-list-cycle-ii/

Linked List Cycle II

[code]Given a linked list, return the node where the cycle begins. If there is no cycle, return null.

Note: Do not modify the linked list.

Follow up:
Can you solve it without using extra space?


解法(Java):

[code]/**
 * 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) {
            return null;
        }
        ListNode slow = head;
        ListNode fast = head.next;
        while (slow != null && fast != null && slow != fast) {
            // if (slow == fast) {
            //     temp = slow;
            //     break;
            // }
            slow = slow.next;
            fast = fast.next == null ? fast.next : fast.next.next;
        }
        if (slow == fast) {
            slow = head;
            fast = fast.next;
            while (slow != fast) {
                slow = slow.next;
                fast = fast.next;
            }
            return slow;
        }
        return null;
    }
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: