[勇者闯LeetCode] 142. Linked List Cycle II
2017-05-19 23:16
429 查看
[勇者闯LeetCode] 142. Linked List Cycle II
Description
Given a linked list, return the node where the cycle begins. If there is no cycle, returnnull.
Information
Tags: Linked List | Two PointersDifficulty: 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 = None class 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
相关文章推荐
- [勇者闯LeetCode] 160. Intersection of Two Linked Lists
- [勇者闯LeetCode] 26. Remove Duplicates from Sorted Array
- [勇者闯LeetCode] 125. Valid Palindrome
- [勇者闯LeetCode] 11. Container With Most Water
- [勇者闯LeetCode] 129. Sum Root to Leaf Number
- [勇者闯LeetCode] 101. Symmetric Tree
- [勇者闯LeetCode] 69. Sqrt(x)
- [勇者闯LeetCode] 9. Palindrome Number
- [勇者闯LeetCode] 136. Single Number
- [勇者闯LeetCode] 104. Maximum Depth of Binary Tree
- [勇者闯LeetCode] 53. Maximum Subarray
- [勇者闯LeetCode] 13. Roman to Integer
- [勇者闯LeetCode] 141. Linked List Cycle
- [勇者闯LeetCode] 111. Minimum Depth of Binary Tree
- [勇者闯LeetCode] 28. Implement strStr()
- [勇者闯LeetCode] 58. Length of Last Word
- [勇者闯LeetCode] 167. Two Sum II - Input array is sorted
- [勇者闯LeetCode] 189. Rotate Array
- [勇者闯LeetCode] 215. Kth Largest Element in an Array
- [勇者闯LeetCode] 121. Best Time to Buy and Sell Stock