141. Linked List Cycle [easy] (Python)
2016-05-27 14:37
417 查看
题目链接
https://leetcode.com/problems/linked-list-cycle/题目原文
Given a linked list, determine if it has a cycle in it.Follow up:
Can you solve it without using extra space?
题目翻译
给定一个链表,判断其中是否有环。进一步:你能在不使用额外空间的情况下解决吗?
思路方法
思路一
倘若不考虑进一步的要求。顺序遍历链表所有节点,若出现重复访问则说明有环,否则说明无环。这里注意不能用list保存访问过的节点,查找太慢了;用dict保存还要考虑到键不能是对象,所以这里采取以对象的id作为键的做法。代码
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def hasCycle(self, head): """ :type head: ListNode :rtype: bool """ map = {} while head: if id(head) in map: return True else: map[id(head)] = True head = head.next return False
说明
上面的方法用了O(n)的额外空间,下面我们讨论O(1)空间的算法。
思路二
快慢指针法。定义两个指针:快指针每次走一步;慢指针每次走两步。依次循环下去,如果链表存在环,那么快慢指针一定会有相等的时候。为了便于理解,你可以想象在操场跑步的两个人,一个快一个慢,那么他们一定会相遇(无论他们的起始点是不是在操场)。
代码
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def hasCycle(self, head): """ :type head: ListNode :rtype: bool """ slow = fast = head while fast and fast.next: slow = slow.next fast = fast.next.next if slow == fast: return True return False
思路三
逆转链表检测法。倘若一个链表存在环,那么将这个链表反转,反转后的链表和原链表具有相同的head。证明起来比较麻烦,可以在纸上画一画来验证。代码
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def hasCycle(self, head): """ :type head: ListNode :rtype: bool """ if head and head.next and head == self.reverseList(head): return True return False def reverseList(self, head): before = after = None while head: after = head.next head.next = before before = head head = after return before
PS: 新手刷LeetCode,新手写博客,写错了或者写的不清楚还请帮忙指出,谢谢!
转载请注明:/article/11857841.html
相关文章推荐
- Python StringIO与cStringIO
- python PDB调试
- python入门(一)
- Python中的 isdigit()方法
- python 发送邮件实例
- Python模块导入
- Python学习备忘1
- Python in Ubuntu Environment
- python的map和reduce函数
- python 正则表达式
- python实现欧拉计划29题
- 用Python玩转数据 Data Processing Using Python 南京大学笔记一:Python猜数字游戏
- Python3 的异常处理
- python实现用程序给自己发邮件
- Python 字符学习1
- Python安装第三包遇到Unable to find vcvarsall.bat
- Python学习笔记:中文编码问题
- Python入门:类及对象浅析
- reverse string in python
- Python Error: Non-ASCII character '\xe5' in file