題目:輸入乙個鍊錶,輸出該鍊錶中倒數第k個結點。
struct listnode
方法:定義兩個指標。第乙個指標從鍊錶的頭指標開始遍歷向前走k-1,第二個指標保持不動;從第k步開始,第二個指標也開始從鍊錶的頭指標開始遍歷。由於兩個指標的距離保持在k-1,當第乙個(走在前面的)指標到達鍊錶的尾結點時,第二個指標(走在後面的)指標正好是倒數第k個結點。
}上述**的bug:
listnode* findkthtotail(listnode* plisthead, unsigned
int k)
listnode *pahead = plisthead;
listnode *pbehind = null;
for (unsigned
int i = 0; i < k - 1; ++ i)
else
}pbehind = plisthead;
while (pahead->m_pnext != null)
return pbehind;
}
測試用例: 鍊錶中倒數第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...
鍊錶中倒數第k個節點
acwing打卡活動 劍指offer 打卡活動 周二第十題 鍊錶中倒數第k個節點 definition for singly linked list.public class listnode 思路 設列表總結點數為n,則n k 1 為該列表的倒數第k個節點 如 n 10,k 2,則 10 2 1 ...
鍊錶中倒數第K個節點
輸入乙個鍊錶,輸出該鍊錶中倒數第k個結點。方法一 先算出節點個數count,然後遍歷到count k,便是倒數第k個。class solution int length count k if k count return 0 for int i 0 inext return data 方法二 快慢指...