您的位置:首页 > 编程语言 > Go语言

[勇者闯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, 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 = 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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  algorithm leetcode