题目描述
输入一个链表,输出该链表中倒数第k个结点。
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}*/
public class Solution {
/**
* head到tempTail是一把长度为k的尺子,当tempTail到达链表的末端时,
* head就到达了倒数第k个节点
* */
public ListNode FindKthToTail(ListNode head,int k) {
ListNode tempTail = head;
if (k<=0||head==null) {
return null;
}
for (int i=1; i<k; ++i) {
if (tempTail.next!=null) {
tempTail = tempTail.next;
} else {
return null;
}
}
while (tempTail.next!=null) {
tempTail = tempTail.next;
head = head.next;
}
return head;
}
}