1 #初始化链表的结点 2 class Node(): 3 def __init__(self,item): 4 self.item = item 5 self.next = None 6 7 #传入头结点,获取整个链表的长度 8 def length(headNode): 9 if headNode == None: 10 return None 11 count = 0 12 currentNode =headNode 13 #尝试了一下带有环的链表,计算长度是否会死循环,确实如此,故加上了count限制 = =|| 14 while currentNode != None and count <=1000: 15 count+=1 16 currentNode = currentNode.next 17 return count 18 19 #获取倒数第K个结点的值,传入头结点和k值 20 def findrKnode(head,k): 21 if head == None: 22 return None 23 #如果长度小于倒数第K个值,则返回通知没有这么长 24 elif length(head)<k: 25 print("链表长度没有倒数第"+str(k)+"数") 26 return None 27 else: 28 #设置两个针,一个快,一个慢,都指向头结点 29 fastPr = head 30 lowPr = head 31 count = 0 32 #让fastPr先走k个长度 33 while fastPr!=None and count<k: 34 count+=1 35 fastPr = fastPr.next 36 #此时fastPr和lowPr同速前进,当fastPr走到尾部,lowPr此处的值正好为倒数的k值 37 while fastPr !=None: 38 fastPr = fastPr.next 39 lowPr = lowPr.next 40 return lowPr 41 42 if __name__ == "__main__": 43 node1 = Node(1) 44 node2 = Node(2) 45 node3 = Node(3) 46 node4 = Node(4) 47 node5 = Node(5) 48 node6 = Node(6) 49 node7 = Node(7) 50 node8 = Node(8) 51 node9 = Node(9) 52 node10 = Node(10) 53 node1.next = node2 54 node2.next = node3 55 node3.next = node4 56 node4.next = node5 57 node5.next = node6 58 node6.next = node7 59 node7.next = node8 60 node8.next = node9 61 node9.next = node10 62 print(findrKnode(node1,5).item)
时间: 2024-10-19 07:32:25