您的位置:首页 > 编程语言 > Python开发

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