题解 | #判断链表中是否有环#
判断链表中是否有环
http://www.nowcoder.com/practice/650474f313294468a4ded3ce0f7898b9
两种方法
第一种:占用一个内存位置,循环遍历链表每一个值,每遍历一个值就给这个值标记
如果遇到一个已标记过的,说明有环
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
#
#
# @param head ListNode类
# @return bool布尔型
#
class Solution:
def hasCycle(self , head ):
# write code here
cur = head
while cur:
if cur.val != 1000001:
cur.val = 1000001
cur = cur.next
else:
return True
return False 第二种:定义快慢指针 慢指针每次走1步,快指针每次走两步,如果快慢指针能够相遇,说明有环
需要注意如果为空链表或者只有一个元素的链表直接返回无环
此外只要快慢指针不相遇就继续循环,但是如果快指针当前或者下一届点为空则说明无环也返回false
否则换回True
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
#
#
# @param head ListNode类
# @return bool布尔型
#
class Solution:
def hasCycle(self , head ):
# write code here
##用两个指针 快慢指针,如果指针能相遇说明存在环
if not head or not head.next:
return False
slow= head
fast = head.next
while fast != slow:
if not fast or not fast.next:
return False
fast = fast.next.next
slow = slow.next
return True

