14 鍊錶中倒數第k個節點

2021-10-01 15:56:06 字數 1490 閱讀 9377

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

題目思路:除了以下兩種方法,還想到一種方法:將鍊錶倒序,然後找到正數第k個節點,其實這種方法是不行的,因為每個節點都有兩個屬性:next、val,倒敘後得到的正數第k個節點,雖然val相同,但是next是不同的.

python 方法1: 設定兩個指標,乙個先走k-1步,然後兩個同時走,當先走的到達鍊錶尾時,另乙個到達倒數第k個:

class

solution

:def

findkthtotail

(self, head, k)

:if head is

none

or k <=0:

return

none

temp1 = head

temp2 = head

while k >1:

if temp1.

next

isnot

none

: temp1 = temp1.

next

k -=

1else

:return

none

while temp1.

next

: temp1 = temp1.

next

temp2 = temp2.

next

return temp2

python 方法2:獲取鍊錶長度,從而可以得到倒數第k個節點是正數第多少個:
class

solution

:def

findkthtotail

(self, head, k)

:# 鍊錶節點總數

number =

0 cur = head

while cur:

number +=

1 cur = cur.

next

# 倒數第k個節點在鍊錶中正數第多少個

index = number - k

if index <0:

return

none

temp = head

while index >0:

temp = temp.

next

index -=

1return temp

c++:

class

solution

listnode *ptail = plisthead;

listnode *phead = plisthead;

// phead 節點指標向後移動k-1步

while

(k>1)

else

}while

(phead-

>next)

return ptail;}}

;

(14)鍊錶倒數第k個節點

輸入乙個鍊錶,輸出該鍊錶中倒數第k個結點。使用快慢指標,乙個指標比另乙個指標快k步,當其到末尾時,最後乙個數恰好到達了倒數第k步 題目 輸入乙個鍊錶,輸出該鍊錶中倒數第k個結點。public class test14 public static class listnode 這是乙個快慢指標的題,我...

鍊錶中倒數第k個節點

題目 輸入乙個鍊錶,輸出該鍊錶中倒數第k個結點。struct listnode方法 定義兩個指標。第乙個指標從鍊錶的頭指標開始遍歷向前走k 1,第二個指標保持不動 從第k步開始,第二個指標也開始從鍊錶的頭指標開始遍歷。由於兩個指標的距離保持在k 1,當第乙個 走在前面的 指標到達鍊錶的尾結點時,第二...

鍊錶中倒數第k個節點

輸入乙個鍊錶,輸出該鍊錶中倒數第k個結點。ac class solution def findkthtotail self,head,k write code here 將每個節點存在棧裡,選取stack中第k個值 stack while head head head.next if k len s...