leetcode:142. Linked List Cycle II(Java)解答
Posted boy_nihao
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode:142. Linked List Cycle II(Java)解答相关的知识,希望对你有一定的参考价值。
转载请注明出处: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)解答的主要内容,如果未能解决你的问题,请参考以下文章
LeetCode-142-Linked List Cycle II
LeetCode 141, 142. Linked List Cycle I+II
leetcode-142. Linked List Cycle II
LeetCode142. Linked List Cycle II