題目描述:輸入乙個鍊錶,輸出該鍊錶中倒數第k個結點。解題思路:
1. 先遍歷鍊錶,獲得鍊錶中的總結點數。
2. 倒數第k個元素,即為順數第 size - k + 1 個元素。
3. 遍歷鍊錶,獲得第 size - k + 1的元素。
/*
public class listnode
}*/public
class
solution
// 統計鍊錶中所有節點數
listnode current = head;
int count = 0;
while(current != null)
// 判斷 k 是否合法
if(k > count)
int offset = count - k + 1;
current = head;
// 當 offset 變為 1 的時候,就找到了這個結點
while(offset != 1)
return current;
}}
輸入乙個鍊錶,輸出該鍊錶中倒數第k個結點。
1,問題 輸入乙個鍊錶,輸出該鍊錶中倒數第k個結點。2,想法都在 裡標註了 struct listnode class solution int count 0 listnode temp plisthead while plisthead int m count k 倒數第k個,是順數第count...
輸入乙個鍊錶,輸出該鍊錶中倒數第k個結點
思路 兩個指標,先讓第乙個指標和第二個指標都指向頭結點,然後再讓第乙個指正走 k 1 步,到達第k個節點。然後兩個指標同時往後移動,當第乙個結點到達末尾的時候,第二個結點所在位置就是倒數第k個節點了。public class solution public listnode findkthtotai...
輸入乙個鍊錶,輸出該鍊錶中倒數第k個結點
輸入乙個鍊錶,輸出該鍊錶中倒數第k個結點 一,先排除掉非法情況,鍊錶為空和k值非法 二,計算鍊錶長度size 三,得到倒數第k個結點需要向後走的步數 steps size k 四,向後走steps步,得到倒數第k個結點 public class listnode public class solut...