題目描述
輸入一個(gè)鏈表黍聂,輸出該鏈表中倒數(shù)第k個(gè)結(jié)點(diǎn)。
思路
1.注意考慮異常情況
2.先選出鏈表的長度length粱哼,則倒數(shù)第K個(gè)節(jié)點(diǎn)即正數(shù)第length-k個(gè)
代碼
public class Solution {
public ListNode FindKthToTail(ListNode head,int k) {
ListNode node = new ListNode(-1);
int length = 0;
int i = 0;
if (head == null || k == 0) {
return null;
}
node = head;
while (node != null) {
length++;
node = node.next;
}
// System.out.println(length);
if (k > length) {
return null;
}
i = length - k;
node = head;
while (i != 0) {
node = node.next;
i--;
}
return node;
}
}