链表倒数第k个节点 python_[宜配屋]听图阁

page-header-to-2021-08-21.jpg

本文实例讲述了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)

print("链表长度没有倒数第"+str(k)+"数")

return None

else:

#设置两个针,一个快,一个慢,都指向头结点

fastPr = head

lowPr = head

count = 0

#让fastPr先走k个长度

while fastPr!=None and count

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程序设计有所帮助。

page-footer-to-2021-08-21.jpg

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值