python实现获取单向链表倒数第k个结点的值示例
作者:鲸落丶 时间:2022-10-12 17:38:10
本文实例讲述了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程序设计有所帮助。
来源:https://www.cnblogs.com/kunpengv5/p/7784760.html
标签:python,单向链表
0
投稿
猜你喜欢
vue实现联动选择
2024-05-22 10:42:28
Mysql日期和时间函数大全
2011-03-08 09:52:00
Python设计模式中的策略模式详解
2023-09-03 09:26:26
PyCharm 光标变成黑块的解决方式
2023-11-12 11:02:48
Python编写淘宝秒杀脚本
2021-01-31 23:23:42
微信小程序实现滑动删除效果
2024-04-19 10:03:45
用Python画小女孩放风筝的示例
2021-11-20 09:40:25
Python异常处理操作实例详解
2023-05-06 11:31:05
对Python3之方法的覆盖与super函数详解
2023-08-25 19:05:28
python爬虫开发之使用Python爬虫库requests多线程抓取猫眼电影TOP100实例
2021-02-25 11:13:42
python判断字符串是否包含子字符串的方法
2021-01-04 12:48:03
CentOS 7上为PHP5安装suPHP的方法(彭哥)
2024-03-24 23:34:12
Oracle中pivot函数图文实例详解
2023-07-12 22:13:49
详解Python执行py文件是否需要可执行权限
2021-01-19 10:52:53
Python curses内置颜色用法实例
2021-07-27 02:41:35
js使用eval解析json(js中使用json)
2024-04-19 10:00:31
事件检测
2009-04-11 18:03:00
Go语言集成开发环境IDE详细安装教程
2024-04-25 15:26:12
超实用的 30 段 Python 案例
2021-11-08 22:51:26
Python基于Serializer实现字段验证及序列化
2023-07-19 21:50:36