LeetCode 142

Posted Juntaran

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode 142相关的知识,希望对你有一定的参考价值。

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?

 

 1 /*************************************************************************
 2     > File Name: LeetCode142.c
 3     > Author: Juntaran
 4     > Mail: [email protected]
 5     > Created Time: Mon 16 May 2016 19:46:12 PM CST
 6  ************************************************************************/
 7 
 8 /*************************************************************************
 9     
10     Linked List Cycle II
11     
12     Given a linked list, return the node where the cycle begins. 
13     If there is no cycle, return null.
14 
15     Note: Do not modify the linked list.
16 
17     Follow up:
18     Can you solve it without using extra space?
19 
20  ************************************************************************/
21 
22 #include <stdio.h>
23 
24 /**
25  * Definition for singly-linked list.
26  * struct ListNode {
27  *     int val;
28  *     struct ListNode *next;
29  * };
30  */
31 struct ListNode *detectCycle(struct ListNode *head)
32 {
33 
34     struct ListNode *fast = head;
35     struct ListNode *slow = head;
36 
37     int count1 = 0;
38     int count2 = 0;
39     while( slow && fast && fast->next )
40     {
41         fast = fast->next->next;
42         slow = slow->next;
43 
44         if( slow == fast )
45         {
46             slow = head;
47             while( slow != fast )
48             {
49                 slow = slow->next;
50                 fast = fast->next;
51             }
52             return slow;
53         }
54     }
55     return NULL;
56 }

 

以上是关于LeetCode 142的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode141 Linked List Cycle. LeetCode142 Linked List Cycle II

[JavaScript 刷题] 双指针 - leetcode 142 & leetcode 287

[JavaScript 刷题] 双指针 - leetcode 142 & leetcode 287

LeetCode Java刷题笔记—142. 环形链表 II

LeetCode 142

LeetCode 142 链表 Linked List Cycle II