使用快慢指针的思想进行查找即可。
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList():
def __init__(self):
self.head: Node = None
def printll(self):
node = self.head
while node:
print(node.data, end=' ')
node = node.next
print()
def append(self, new_node):
node = self.head
if node is None:
self.head = new_node
return
while node.next is not None:
node = node.next
node.next = new_node
def get_backward_node(self, n=2):
if self.head is None:
raise ValueError('Linked list empty!')
fast = self.head
for _ in range(n-1):
if fast.next is not None:
fast = fast.next
else:
raise ValueError('size of n too big!')
slow = self.head
while fast.next is not None:
slow = slow.next
fast = fast.next
print('get_backward_node:', slow.data)
return slow
def get_middle(self):
if self.head is None:
raise ValueError('Linked list empty!')
slow = self.head
fast = self.head
while fast != None and fast.next != None:
fast = fast.next.next
slow = slow.next
print(slow.data)
def has_loop(self):
if self.head is None:
raise ValueError('Linked list empty!')
slow = self.head
fast = self.head.next
while slow != None and fast != None and fast.next != None:
print('fast: ', fast.data, 'slow: ', slow.data)
if fast is slow or fast.next is slow:
print('存在闭环')
return True
fast = fast.next.next
slow = slow.next
print('不是循环列表')
return False
# 合并两个有序列表
def loop_merge_sort(l1, l2):
tmp = []
while len(l1) > 0 and len(l2) > 0:
if l1[0] < l2[0]:
tmp.append(l1[0])
del l1[0]
else:
tmp.append(l2[0])
del l2[0]
print(l1, l2)
tmp.extend(l1)
tmp.extend(l2)
return tmp
if __name__ == "__main__":
node1 = Node(1)
node2 = Node(2)
node3 = Node(3)
node4 = Node(4)
node5 = Node(5)
node6 = Node(6)
node7 = Node(7)
linked = LinkedList()
linked.append(node1)
linked.append(node2)
linked.append(node3)
linked.append(node4)
linked.append(node5)
linked.append(node6)
# linked.append(node2)
linked.append(node7)
if not linked.has_loop():
linked.printll()
linked.get_middle()
linked.get_backward_node(2)
print(loop_merge_sort([1,2,3, 6], [1, 3, 8, 9]))