博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[LeetCode] Linked List Cycle II
阅读量:6261 次
发布时间:2019-06-22

本文共 1107 字,大约阅读时间需要 3 分钟。

Again, a classic interview question of linked list. Similar to Linked List Cycle, we maintain two pointers fast and slow: fast move two steps at one time while slow moves one step at a time. Once they become NULL, return NULL (no cycle). Otherwise, they will equal at some time. At this time, move any one of them back to head and then move both of them one step at a time. Then they will meet at the same node again. At this time, that node is where the cycle begins. Return it and we are done.

The code is as follows.

1     ListNode* detectCycle(ListNode* head) { 2         ListNode* slow = head; 3         ListNode* fast = head; 4         while (fast && fast -> next) { 5             slow = slow -> next; 6             fast = fast -> next -> next; 7             if (slow == fast) { 8                 slow = head; 9                 while (slow != fast) {10                     slow = slow -> next;11                     fast = fast -> next;12                 }13                 return slow;14             }15         }16         return NULL;17     }

转载于:https://www.cnblogs.com/jcliBlogger/p/4562139.html

你可能感兴趣的文章
int类型究竟占几个字节
查看>>
13.使用toggle()方法绑定多个函数
查看>>
springboot集成redis
查看>>
装饰器的应用-装饰器带参数和不带参数
查看>>
数据库 --> SQL 和 NoSQL 的区别
查看>>
USB学习笔记连载(二十):FX2LP如何实现高速和全速切换(转载)
查看>>
ubuntu下搭建JAVA开发环境【转】
查看>>
和菜鸟一起学c之gcc编译过程及其常用编译选项【转】
查看>>
Linux内核驱动--硬件访问I/O【原创】
查看>>
使用NSUserDefaults保存自定义对象(转)
查看>>
linux上查看swf文件.靠谱
查看>>
sql server两种分页方法
查看>>
一本离线的百科全书,当然无法和一本在线的百科全书抗衡。所谓的常识,在你的思考中被重构,根源就在于在线的崛起。...
查看>>
Floyd算法
查看>>
CentOS 6.4下安装Oracle 11gR2
查看>>
linux建立用户 详细
查看>>
jquery获取radio的值
查看>>
创建索引
查看>>
jQuery基础-创建HTML
查看>>
spring boot 热部署
查看>>