[勇者闯LeetCode] 142. Linked List Cycle II
来源:互联网 发布:illustrator软件下载 编辑:程序博客网 时间:2024/06/05 15:36
[勇者闯LeetCode] 142. Linked List Cycle II
Description
Given a linked list, return the node where the cycle begins. If there is no cycle, return
null
.
Information
- Tags: Linked List | Two Pointers
- Difficulty: Medium
Solution
使用快慢指针fast和slow从链头开始扫描,fast每次走两步,slow每次走一步,当fast与slow相遇时说明有环,此时将fast重新从链头开始扫描,且将扫描步长改为一步,那么可证明,当fast和slow两次相遇时,它们所指向的就是环的起点。
Python Code
# Definition for singly-linked list.# class ListNode(object):# def __init__(self, x):# self.val = x# self.next = Noneclass Solution(object): def detectCycle(self, head): """ :type head: ListNode :rtype: ListNode """ 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
阅读全文
0 0
- [勇者闯LeetCode] 142. Linked List Cycle II
- [勇者闯LeetCode] 141. Linked List Cycle
- [LeetCode]141. Linked List Cycle【&142. Linked List Cycle II】
- leetcode--141. Linked List Cycle&&142. Linked List Cycle II
- LeetCode 141. Linked List Cycle && 142. Linked List Cycle II
- 142. Linked List Cycle II leetcode list
- LeetCode 142. Linked List Cycle II
- [LeetCode]142.Linked List Cycle II
- [leetcode] 142.Linked List Cycle II
- [leetcode] 142. Linked List Cycle II
- leetcode 142. Linked List Cycle II
- [Leetcode]142. Linked List Cycle II @python
- [LeetCode]142. Linked List Cycle II
- 142. Linked List Cycle II LeetCode
- LeetCode:142. Linked List Cycle II
- LeetCode--142. Linked List Cycle II
- LeetCode 142. Linked List Cycle II
- LeetCode 142. Linked List Cycle II
- 接口和抽象类有什么区别?
- spring jpa 获取自增id
- android 4.3选择图片“无法加载图片问题”
- 解决div与span等inline元素同行后高度不一致问题
- ftp详解
- [勇者闯LeetCode] 142. Linked List Cycle II
- 重命名文件或文件夹
- OpenCV 2.4.10 +VS2013 开发环境配置
- C++作业7
- 《effective c++》读书笔记
- ArrayList
- js实现Tomcat游戏
- Redis
- 实现多线程的三种方法