question:输入一个链表,输出该链表中倒数第k个结点。
resolution:
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}
public ListNode FindKthToTail(ListNode head,int k) {
if (head == null) return null;//考虑特殊情况
int len = 1;//注意起始值
int i = 1;//起始值不为0
ListNode tempHead = head;
ListNode result = null;
while (tempHead.next != null){
tempHead = tempHead.next;
len++;
}
int index = len - k +1;
while (head != null){//不用head.next==null,否则遍历不到最后一个节点
if(i == index){//先判断,再遍历和自增,注意先后顺序
result = head;
break;
}
head = head.next;
i++;
}
return result;
}