leetcode 【 Linked List Cycle II 】 python 实现
2015-01-03 15:58
453 查看
公司和学校事情比较多,隔了好几天没刷题,今天继续刷起来。
题目:
Given a linked list, return the node where the cycle begins. If there is no cycle, return
Follow up:
Can you solve it without using extra space?
代码:oj 测试通过 Runtime: 596 ms
思路:
主要利用快慢指针的思想。
自己没太多思路,直接参考下面几篇靠谱的日志:
http://www.cnblogs.com/hiddenfox/p/3408931.html http://blog.csdn.net/cs_guoxiaozhu/article/details/14209743
如果链表中没有循环自不必说;
如果有循环:
快慢指针第一次相遇之后,把一个指针重新指向head,然后两个指针相同速度往前走;
两个指针第二次相遇的位置就是循环开始的位置
Tips:
自己在实现的时候犯了一个错误,迭代p1 p2 找到二次相遇的位置 直接返回p1,这里迷糊了:应该迭代p1 p2判断p1.next与p2.next相等,再返回p1.next;这样返回的点才是原来链表中的,而不是构造出来的p1。
题目:
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?
代码:oj 测试通过 Runtime: 596 ms
# 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): if head is None or head.next is None: return None dummyhead = ListNode(0) dummyhead.next = head p1 = ListNode(0) p1.next = head p2 = ListNode(0) p2.next = head first_meet = None while p1 is not None and p2 is not None: if p1 == p2: first_meet = p1 break else: p1 = p1.next p2 = p2.next if p2 is not None: p2 = p2.next result = None if first_meet is None: return None else: p2 = dummyhead while p1 is not None and p2 is not None: if p1.next == p2.next: result = p1.next break else: p1 = p1.next p2 = p2.next return result
思路:
主要利用快慢指针的思想。
自己没太多思路,直接参考下面几篇靠谱的日志:
http://www.cnblogs.com/hiddenfox/p/3408931.html http://blog.csdn.net/cs_guoxiaozhu/article/details/14209743
如果链表中没有循环自不必说;
如果有循环:
快慢指针第一次相遇之后,把一个指针重新指向head,然后两个指针相同速度往前走;
两个指针第二次相遇的位置就是循环开始的位置
Tips:
自己在实现的时候犯了一个错误,迭代p1 p2 找到二次相遇的位置 直接返回p1,这里迷糊了:应该迭代p1 p2判断p1.next与p2.next相等,再返回p1.next;这样返回的点才是原来链表中的,而不是构造出来的p1。
相关文章推荐
- 【算法分析】如何理解快慢指针?判断linked list中是否有环、找到环的起始节点位置。以Leetcode 141. Linked List Cycle, 142. Linked List Cycle II 为例Python实现
- LeetCode 92 Reverse Linked List II (Python详解及实现)
- leetcode 【 Reverse Linked List II 】 python 实现
- leetcode Linked List Cycle II python
- [Leetcode][python]Linked List Cycle/Linked List Cycle II
- 【LeetCode-面试算法经典-Java实现】【142-Linked List Cycle II(单链表中有环II)】
- LeetCode 142 — Linked List Cycle II(C++ Java Python)
- [leetcode]Linked List Cycle II @ Python
- leetcode 【 Linked List Cycle 】 python 实现
- [LeetCode]题解(python):142-Linked List Cycle II
- LeetCode 之 Linked List Cycle I II — C++ 实现
- leetcode linked-list-cycle(i 、ii)(java实现)
- LeetCode之Linked List Cycle II
- LeetCode:Linked List Cycle II
- LeetCode: Linked List Cycle II
- leetcode -- Linked List Cycle II
- LeetCode - Linked List Cycle II
- [LeetCode]Linked List Cycle II
- LeetCode — Linked List Cycle II 解题报告
- [leetcode]Linked List Cycle II