# Python中的实例

# 定义单节点
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None


head = ListNode(0) #值为0


# leetcode的应用

## 142. Linked List Cycle II

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

# 方法一、把遍历的指针都保存起来，如果有重复就返回重复节点，没有重复，链表到底了就返回None
class Solution(object):
"""
:rtype: ListNode
"""

dict = {}
i = 0

while cur:
dict[cur] = i
cur = cur.next
if cur in dict:
return cur
i += 1

return None

# 方法二、快慢指针，两个不同遍历速度的指针，如果指针重合了，说明有重复，然后再循环找出第一个重复的节点（需要数学证明）
class Solution(object):
"""
:rtype: ListNode
"""

while fast and fast.next and slow:  # 如果不符合判断条件，则无环，返回None
slow = slow.next
fast = fast.next.next
if slow == fast:   #有环，打断进入下一个循环
break
else:
return None

while 1:   # 复制一个头节点，再重新走到重合
if temp == slow:
return temp
temp = temp.next
slow = slow.next

• 结果：
1. 方法一、
2. 方法二、

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

# 方法一、循环反转
class Solution(object):
"""
:rtype: ListNode
"""

return None

while temp:
temp = cur_1.next
cur_1.next = cur_0
cur_0 = cur_1
cur_1 = temp

return cur_0

# 方法一的改进
class Solution(object):
"""
:rtype: ListNode
"""

pre = None
fro = None

while cur:   # 设置三个节点的变量，不断变换
fro = cur.next
if fro == None:
cur.next = pre
pre = cur
cur = fro

# 方法二：递归

class Solution(object):
"""
:rtype: ListNode
"""

while cur.next:
cur = cur.next