這篇文章將為大家詳細講解有關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個結點的值”這篇文章就分享到這里了,希望以上內容可以對大家有一定的幫助,使各位可以學到更多知識,如果覺得文章不錯,請把它分享出去讓更多的人看到。
當前文章:python如何實現獲取單向鏈表倒數第k個結點的值-創新互聯
URL鏈接:http://www.yijiale78.com/article42/dehdec.html
成都網站建設公司_創新互聯,為您提供標簽優化、App設計、網站設計公司、動態網站、App開發、品牌網站建設
聲明:本網站發布的內容(圖片、視頻和文字)以用戶投稿、用戶轉載內容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網站立場,如需處理請聯系客服。電話:028-86922220;郵箱:631063699@qq.com。內容未經允許不得轉載,或轉載時需注明來源: 創新互聯