Leetcode #142 Linked List Cycle II
2015-09-10 09:51
288 查看
Given a linked list, return the node where the cycle begins. If there is no cycle, return
Note: Do not modify the linked list.
Follow up:
Can you solve it without using extra space?
Difficulty: Medium
如果不用额外的space,这里有一个小技巧。
假设我们在第一次p = pNext时,p走了N步,pNext走了2N步,两个指针的步数之差正好就是一个cycle的步数,也就是2N-N = N。
设进入这个循环需要X步,那么此时指针p和pNext离cycle的起点正好差X步(可以画个图想想)。所以,让p回到head,同时开始走,每次都只走一步,下一次相遇就是cycle的入口。
null.
Note: Do not modify the linked list.
Follow up:
Can you solve it without using extra space?
Difficulty: Medium
如果不用额外的space,这里有一个小技巧。
假设我们在第一次p = pNext时,p走了N步,pNext走了2N步,两个指针的步数之差正好就是一个cycle的步数,也就是2N-N = N。
设进入这个循环需要X步,那么此时指针p和pNext离cycle的起点正好差X步(可以画个图想想)。所以,让p回到head,同时开始走,每次都只走一步,下一次相遇就是cycle的入口。
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def detectCycle(self, head): """ :type head: ListNode :rtype: ListNode """ flag = 0 p = head pNext=head while (p is not None) and (pNext is not None) and flag==0: if p.next is None or pNext.next is None: return None p = p.next pNext = pNext.next.next if p==pNext: flag = 1 if flag == 0: return None p = head; while p!=pNext: p = p.next pNext = pNext.next return p
相关文章推荐
- cocos2d-js中监听帧事件时不要忘了this
- javaMail接收邮件
- 解决Eclipse发布webproject, jar无法发布到tomcat lib目录下的问题
- -fobjc-arc,使ARC与非ARC一块工作
- java logger
- mysql ftp或者镜像站点,提供各个版本资源
- 利用 Tinyproxy 搭建 HTTP(S) 代理
- 兔子--service的使用步骤
- Xcode 升级后,常常遇到的遇到的警告、错误,解决方法
- JQuery.getJSON 从aspx页面返回JSON数据
- sql server 与C#数据类型对应表
- 简单PHPexcel
- Samba配置文件常用参数详解
- 通用ListView Adapter
- JS判断客户端是否是iOS或者Android
- VS2010:error LNK2001: 无法解析的外部符号 ___argv
- win7下安装配置tomcat,java运行环境
- GMM混合高斯模型的C++代码(一)
- 零基础学python-14.3 python的文档资源:help函数
- 游戏中的常用算法