題目描述:輸入乙個鍊錶,輸出該鍊錶中倒數第k個結點
/**
* 思路:1. 得到鍊錶的長度
* 2. 通過觀察可以發現當 cur 從 head 開始到倒數第 k 個節點所迴圈的次數 == len - k
* 3. 所以退出迴圈時 cur 指的就是題目所求的節點
*/public
class
solution
return len;
}public listnode findkthtotail
(listnode head,
int k)
int len =
length
(head);if
(k <= len)
return cur;
}return null;
}}
//思路:用兩個引用,乙個走得快,乙個走的慢,當 front==null 時,back 所指就是輸出節點
public
class
solution
listnode front = head;
listnode back = head;
for(
int i=
0;i) front = front.next;
}while
(front!=null)
return back;
}}
鍊錶中倒數第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...
鍊錶中倒數第k個節點
acwing打卡活動 劍指offer 打卡活動 周二第十題 鍊錶中倒數第k個節點 definition for singly linked list.public class listnode 思路 設列表總結點數為n,則n k 1 為該列表的倒數第k個節點 如 n 10,k 2,則 10 2 1 ...