[leetcode] Linked List Cycle II

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?

轉自:http://www.mysjtu.com/page/M0/S951/951294.html

思路:對於linked list cycle I, 思路很簡單,快慢指針相遇則有循環。但是要找到循環的起點,就有些麻煩

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    # @param head, a ListNode
    # @return a list node
    def detectCycle(self, head):
        slow = head
        fast = head
        while fast != None and fast.next != None:
            fast = fast.next.next
            slow = slow.next
            if fast != None and slow != None and fast == slow:
                break
        if fast == None or fast.next == None:
            return None
        slow = head
        while fast != slow:
            slow = slow.next
            fast = fast.next
        return fast

,具體思路參考

http://www.mysjtu.com/page/M0/S951/951294.html

代碼:


發佈了33 篇原創文章 · 獲贊 0 · 訪問量 7206
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章