码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2015-12-28 10:37:48      阅读:233      评论:0      收藏:0      [点我收藏+]

标签:

转载请注明出处:z_zhaojun的博客
原文地址:http://blog.csdn.net/u012975705/article/details/50412899
题目地址:https://leetcode.com/problems/linked-list-cycle-ii/

Linked List Cycle II

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):

/**
 * 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;
    }
}

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

标签:

原文地址:http://blog.csdn.net/u012975705/article/details/50412899

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!