给定一个链表,判断它是否有环

如何判断是否有环?设置两个头结点指针,一个走的快,一个走的慢,那么若干步以后,快的指针总会超过慢的指针一圈。(python代码)

 1 """
 2 Definition of ListNode
 3 class ListNode(object):
 4 
 5     def __init__(self, val, next=None):
 6         self.val = val
 7         self.next = next
 8 """
 9 class Solution:
10     """
11     @param head: The first node of the linked list.
12     @return: True if it has a cycle, or false
13     """
14     def hasCycle(self, head):
15         # write your code here
16         slow=head
17         fast=head
18         while fast!=None and fast.next!=None:
19             slow=slow.next
20             fast=fast.next.next
21             if slow==fast:
22                 break
23         if fast==None or fast.next==None:
24             return False
25         else:
26             return True

 类似代码,大同小异

 1 """
 2 Definition of ListNode
 3 class ListNode(object):
 4 
 5     def __init__(self, val, next=None):
 6         self.val = val
 7         self.next = next
 8 """
 9 class Solution:
10     """
11     @param head: The first node of the linked list.
12     @return: True if it has a cycle, or false
13     """
14     def hasCycle(self, head):
15         # write your code here
16         if head is None:            
17             return False        
18         p1 = head        
19         p2 = head        
20         while True:
21             if p1.next is not None:
22                 p1=p1.next.next
23                 p2=p2.next
24                 if p1 is None or p2 is None:
25                     return False
26                 elif p1 == p2:
27                     return True
28             else:
29                 return False
30         return False

 

posted @ 2016-04-01 19:54  随缘剑客  阅读(351)  评论(0)    收藏  举报