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

原创 2015年12月27日 16:36:19

转载请注明出处: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;
    }
}
版权声明:本文为博主原创文章,转载请注明出处。博客首页:http://blog.csdn.net/u012975705。订阅:http://blog.csdn.net/u012975705/rss/list

[LeetCode] 142. Linked List Cycle II java

/**142. Linked List Cycle II * @param head * @return */ public ListNode detectCy...

LeetCode 142. Linked List Cycle II

要求用O(1)的空间确定链表中环的起始结点: 使用slow, fast指针,

[Leetcode-142] Linked List Cycle II(链表有环详细分析)

环的长度是多少? 如何找到环中第一个节点(即Linked List Cycle II)? 如何将有环的链表变成单链表(解除环)? 如何判断两个单链表是否有交点?如何找到第一个相交的节点?...

[leetcode] 142. Linked List Cycle II

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

LeetCode 142 Linked List Cycle II

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

[leetcode] 142. Linked List Cycle II 解题报告

题目链接:https://leetcode.com/problems/linked-list-cycle-ii/ Given a linked list, return the node wher...

[leetcode] 142.Linked List Cycle II

题目: Given a linked list, return the node where the cycle begins. If there is no cycle, return null....

[Leetcode] 142. Linked List Cycle II 解题报告

题目: Given a linked list, return the node where the cycle begins. If there is no cycle, return n...

LeetCode142 Linked List Cycle II

题目链接: https://leetcode.com/problems/linked-list-cycle-ii/ 题目描述:给一个链表,如果有环,找到环开始位置的节点。如果没有环,返回null。...
  • codeTZ
  • codeTZ
  • 2015年12月12日 20:33
  • 271

【leetcode】142. Linked List Cycle II

【leetcode】142. Linked List Cycle II
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:leetcode:142. Linked List Cycle II(Java)解答
举报原因:
原因补充:

(最多只允许输入30个字)