輸出該鍊錶中倒數第k個結點。

2021-10-08 13:29:26 字數 724 閱讀 3283

快慢指標思路

第乙個指標走到k 然後第二個指標開始走

第乙個指標走到尾巴的時候,第二個指標就是當前倒數k節點的指標

# -*- coding:utf-8 -*-

# class listnode:

# def __init__(self, x):

# self.val = x

# self.next = none

class solution:

def findkthtotail(self, head, k):

# write code here

if head==none or k<0:

return none

# 快慢指標,第乙個指標走k個以後,第二個走,如果第乙個為none到頭的時候,第二個就是倒數k

first = head

second = head

i = 0

while i < k:

if first != none:

first = first.next

i = i+1

else:

return none

while first != none:

first = first.next

second = second.next

return second

輸出該鍊錶中倒數第k個結點

思路 有兩種方法 第一種 若有n 個節點,找到倒數第k個就是遍歷正數第n k 1個,但是並不知道有多少個節點所以要花o n 的時間去求n的大小 再去找節點,public static listnode findnode2 listnode head,int k if k n return null ...

輸出鍊錶中倒數第k個結點

題目 輸入乙個單向鍊錶,輸出該鍊錶中倒數第k個結點。鍊錶的倒數第0個結點為鍊錶的尾指標。鍊錶結點定義如下 struct listnode coder lee 20120309 include include using namespace std struct listnode void creat...

輸出鍊錶中倒數第k個結點

鍊錶中倒數第k個結點 題目描述 輸入乙個鍊錶,輸出該鍊錶中倒數第k個結點。思路 定義新結點從頭開始遍歷鍊錶,移動 k 次後停止,再定義新的結點指向煉表頭結點,兩個結點同時後移,直至前乙個為 null。注意 鍊錶可能一開始就是空的。如果 k 等於鍊錶長度,如1 2 3,k 3時應該返回原鍊錶1 2 3...