这篇文章将为大家详细讲解有关python如何实现获取单向链表倒数第k个结点的值,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。
具体如下:
#初始化链表的结点
class Node():
def __init__(self,item):
self.item = item
self.next = None
#传入头结点,获取整个链表的长度
def length(headNode):
if headNode == None:
return None
count = 0
currentNode =headNode
#尝试了一下带有环的链表,计算长度是否会死循环,确实如此,故加上了count限制 = =||
while currentNode != None and count <=1000:
count+=1
currentNode = currentNode.next
return count
#获取倒数第K个结点的值,传入头结点和k值
def findrKnode(head,k):
if head == None:
return None
#如果长度小于倒数第K个值,则返回通知没有这么长
elif length(head)<k:
print("链表长度没有倒数第"+str(k)+"数")
return None
else:
#设置两个针,一个快,一个慢,都指向头结点
fastPr = head
lowPr = head
count = 0
#让fastPr先走k个长度
while fastPr!=None and count<k:
count+=1
fastPr = fastPr.next
#此时fastPr和lowPr同速前进,当fastPr走到尾部,lowPr此处的值正好为倒数的k值
while fastPr !=None:
fastPr = fastPr.next
lowPr = lowPr.next
return lowPr
if __name__ == "__main__":
node1 = Node(1)
node2 = Node(2)
node3 = Node(3)
node4 = Node(4)
node5 = Node(5)
node6 = Node(6)
node7 = Node(7)
node8 = Node(8)
node9 = Node(9)
node10 = Node(10)
node1.next = node2
node2.next = node3
node3.next = node4
node4.next = node5
node5.next = node6
node6.next = node7
node7.next = node8
node8.next = node9
node9.next = node10
print(findrKnode(node1,5).item)
运行结果:
6
关于“python如何实现获取单向链表倒数第k个结点的值”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,使各位可以学到更多知识,如果觉得文章不错,请把它分享出去让更多的人看到。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。