首页 > 其他 > 详细

CCI_Q2.5

时间:2014-03-11 11:45:22      阅读:417      评论:0      收藏:0      [点我收藏+]
本文参考该作者文章当作编程笔记:

作者:Hawstein
出处:http://hawstein.com/posts/ctci-solutions-contents.html

Q:

给定一个循环链表,实现一个算法返回这个环的开始结点。

定义:

循环链表:链表中一个结点的指针指向先前已经出现的结点,导致链表中出现环。

例子:

输入:A -> B -> C -> D -> E -> C [结点C在之前已经出现过]

输出:结点C

思路:见原作者blog:http://hawstein.com/posts/2.5.html

CODE:

bubuko.com,布布扣
 1 #include<stdio.h>
 2 #include"list.h"
 3 #define N 10
 4 struct node *loopstart(struct node *head)
 5 {
 6     if(!head->next)return NULL;
 7     link fast=head,slow=head;
 8     while(fast->next)
 9     {
10         fast=Next(fast);
11         fast=Next(fast);
12         slow=Next(slow);
13         if(fast==slow)
14             break;
15     }
16     if(!fast||!fast->next)return NULL;
17     slow=head;
18     while(fast->next)
19     {
20         fast=Next(fast);
21         slow=Next(slow);
22         if(fast==slow)
23             break;
24     }
25     return fast;
26 }
27 int main()
28 {
29     struct node *head;
30     initNodes(&head);
31     int s[N]={3,2,1,3,5,6,2,6,3,1};
32     int i;
33     for(i=N-1;i>=0;--i)
34     {
35         insertNext(head,newNode(s[i]));
36     }
37     link p=head,q=head;
38     for(i=0;i<N;i++)//第4个点设为环形起点。
39     {
40         p=p->next;
41         if(i==3)
42             q=p;
43     }
44     p->next=q;//最后一个点指向环形起点。
45     p=loopstart(head);
46     if(p)
47         printf("%d\n",Item(p));
48     return 0;
49 }
bubuko.com,布布扣

CCI_Q2.5,布布扣,bubuko.com

CCI_Q2.5

原文:http://www.cnblogs.com/jhooon/p/3589913.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!