码迷,mamicode.com
首页 > 编程语言 > 详细

单向列表的倒数第k个结点的值 python实现

时间:2017-11-04 23:31:05      阅读:247      评论:0      收藏:0      [点我收藏+]

标签:log   fast   初始化   none   取整   pytho   设置   长度   pre   

 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)

单向列表的倒数第k个结点的值 python实现

标签:log   fast   初始化   none   取整   pytho   设置   长度   pre   

原文地址:http://www.cnblogs.com/kunpengv5/p/7784760.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!