题目来源:牛客网--程序员面试金典
解决思路:
- 先求出链表中一共有多少个节点
- 然后在找到倒数第k个节点的位置,并将其返回
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}*/
public class Solution {
public ListNode FindKthToTail(ListNode head,int k) {
ListNode current = head;
int length = 0;
while(current != null){
length += 1;
current = current.next;
}
ListNode tmp = head;
int a = 0;
if(k<= length){
while(a != length - k ){
a++;
tmp = tmp.next;
}
return tmp;
}
else{
return null;
}
}
}