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: JuntaranMail@gmail.com
 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 }

 

转载于:https://www.cnblogs.com/Juntaran/p/5511680.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值