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

2021-09-25 22:27:44 字數 604 閱讀 4053

思路:

有兩種方法:

第一種 若有n』個節點,找到倒數第k個就是遍歷正數第n-k+1個,但是並不知道有多少個節點所以要花o(n)的時間去求n的大小

再去找節點,

public static listnode findnode2(listnode head,int k)

if(k>n)return null;

listnode preh = head;

for(int i = 0;i第二種 :

那兩個指標第乙個指標先出去,間隔k個步驟後第二個節點走出,他們中間始終保持k的間距,當第乙個指標到達尾節點的時候,第二個指標剛好指到倒數第k個節點上

public static listnode findnode(listnode head,int k)

listnode prea = head;

listnode preb = null;

for(int i =0;i else

return null;

}preb = head;

while(prea.next!=null)

return preb;

}

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

快慢指標思路 第乙個指標走到k 然後第二個指標開始走 第乙個指標走到尾巴的時候,第二個指標就是當前倒數k節點的指標 coding utf 8 class listnode def init self,x self.val x self.next none class solution def fin...

輸出鍊錶中倒數第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...