leetcode141 Linked List Cycle

 1 """
 2 Given a linked list, determine if it has a cycle in it.
 3 To represent a cycle in the given linked list, we use an integer pos which represents the position (0-indexed) in the linked list where tail connects to. If pos is -1, then there is no cycle in the linked list.
 4 Example 1:
 5 Input: head = [3,2,0,-4], pos = 1
 6 Output: true
 7 Explanation: There is a cycle in the linked list, where tail connects to the second node.
 8 Example 2:
 9 Input: head = [1,2], pos = 0
10 Output: true
11 Explanation: There is a cycle in the linked list, where tail connects to the first node.
12 Example 3:
13 Input: head = [1], pos = -1
14 Output: false
15 Explanation: There is no cycle in the linked list.
16 """
17 """
18 好题
19 解法一:快慢指针法,自己AC
20 """
21 class ListNode:
22     def __init__(self, x):
23         self.val = x
24         self.next = None
25 
26 class Solution1:
27     def hasCycle(self, head):
28         if not head:
29             return False
30         slow = head
31         fast = head.next
32         while fast:
33             if slow.val == fast.val:
34                 return True
35             if fast.next:
36                 fast = fast.next
37             if slow.val == fast.val:
38                 return True
39             slow = slow.next
40             fast = fast.next
41         return False
42 
43 """
44 解法二:用set()或dict()或list()来存已经遍历过的结点,判断当前结点是否在集合中
45 值得注意的是,set时间最短
46 """
47 
48 class Solution:
49     def hasCycle(self, head: ListNode) -> bool:
50         if not head:
51             return False
52         s = set()
53         cur = head
54         while cur:
55             if cur in s:
56                 return True
57             s.add(cur)
58             cur = cur.next
59         return False
60 """
61 dict的一些方法:
62 dic = {'name':'fuyong','age':29,'job':'none'}
63 dic.setdefault('addr','henan')
64 print(dic) #结果 {'addr': 'henan', 'age': 29, 'name': 'fuyong', 'job': 'none'}
65 dic.update({'addr':'henan'})
66 print(dic) #结果 {'job': 'none', 'addr': 'henan', 'age': 29, 'name': 'fuyong'}
67 dic.pop('job')
68 print(dic)  #结果为:{'age': 29, 'name': 'fuyong'}
69 print(dic.popitem())  #结果为('name', 'fuyong')
70 del dic['job']
71 print(dic) #结果为:{'age': 29, 'name': 'fuyong'}
72 dic.clear()
73 print(dic)   #结果为:{}
74 用来遍历的方法dic.keys() dic.values() dic.items()
75 """
原文地址:https://www.cnblogs.com/yawenw/p/12387407.html