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

Follow up:
Can you solve it without using extra space?

141. Linked List Cycle 的拓展,这题要返回环开始的节点,如果没有环返回null。

解法:双指针,还是用快慢两个指针,相遇时记下节点。参考:willduan的博客

Java:

public class Solution {
public ListNode detectCycle( ListNode head ) {
if( head == null || head.next == null ){
return null;
}
// 快指针fp和慢指针sp,
ListNode fp = head, sp = head;
while( fp != null && fp.next != null){
sp = sp.next;
fp = fp.next.next;
//此处应该用fp == sp ,而不能用fp.equals(sp) 因为链表为1 2 的时候容易
//抛出异常
if( fp == sp ){ //说明有环
break;
}
}
//System.out.println( fp.val + " "+ sp.val );
if( fp == null || fp.next == null ){
return null;
}
//说明有环,求环的起始节点
sp = head;
while( fp != sp ){
sp = sp.next;
fp = fp.next;
}
return sp;
}
}   

Python:

class ListNode:
def __init__(self, x):
self.val = x
self.next = None def __str__(self):
if self:
return "{}".format(self.val)
else:
return None class Solution:
# @param head, a ListNode
# @return a list node
def detectCycle(self, head):
fast, slow = head, head
while fast and fast.next:
fast, slow = fast.next.next, slow.next
if fast is slow:
fast = head
while fast is not slow:
fast, slow = fast.next, slow.next
return fast
return None  

C++:

class Solution {
public:
ListNode *detectCycle(ListNode *head) {
ListNode *slow = head, *fast = head;
while (fast && fast->next) {
slow = slow->next;
fast = fast->next->next;
if (slow == fast) break;
}
if (!fast || !fast->next) return NULL;
slow = head;
while (slow != fast) {
slow = slow->next;
fast = fast->next;
}
return fast;
}
};

  

类似题目:

[LeetCode] 141. Linked List Cycle 链表中的环

All LeetCode Questions List 题目汇总

最新文章

  1. 【转】Oracle索引HINT的使用
  2. Ecstore会员密码加密方式破解
  3. Qt4升级Qt5注意问题
  4. iOS开发——UI篇&文字渐变效果:图层中的mask属性
  5. Linux 修改swap虚拟内存大小
  6. 编写WCF服务时右击配置文件无“Edit WCF Configuration”(编辑 WCF 配置)远程的解决办法
  7. 安装javaUbuntu下安装JDK1.6,并将之设为默认的JDK
  8. AngularJS指令进阶 – ngModelController详解
  9. Lumen框架搭建指南
  10. 搭建Hadoop完全分布式
  11. JDK8安装与配置
  12. Python Selenium 文件上传之SendKeys
  13. 第38次Scrum会议(12/4)【欢迎来怼】
  14. (CoreText框架)NSAttributedString 2
  15. SQL Fundamentals:替代变量(&,&&)以及DEFINE,UNDEFINE,ACCEPT指令
  16. [Kafka] - Kafka Java Consumer实现(二)
  17. centos6.3下yum安装redis
  18. haproxy+keepalived实现高可用负载均衡(转)
  19. ios 更改UITableview group形式 两个section之间的距离
  20. 懒加载 js----例子------图片

热门文章

  1. 基于CentOS7配置ArcGIS enterprise
  2. ReqMan — 需求提取和协同处理工具
  3. BLE——协议层次结构
  4. [Luogu 2386]放苹果
  5. 使用GCOV进行代码覆盖率统计
  6. Combined beamformers for robust broadband regularized superdirective beamforming
  7. Parametric and Nonparametric Algorithms
  8. 微信小程序开发工具“当前系统代理不是安全代理”
  9. Python爬虫进阶 | 多线程
  10. Linux上使用Windows软件