题目描述
输入一个链表,输出该链表中倒数第k个结点。
方法一:基于基数,倒数第k个,是正数的总数-k+1
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}*/
public class Solution {
public ListNode FindKthToTail(ListNode head,int k) {
if(head==null|k<=0){
return null;
}
int count=0;
ListNode pre=head;
while(pre.next!=null){
pre=pre.next;
count++;
}
if(k>count+1){
return null;
}
int num=count+1-k;
for(int i=0;i<num;i++){
head=head.next;
}
return head;
}
}
/**
* 设置两个指针,第一个指针从前走k-1步到达正数第k的节点
* 然后两个指针同时向后遍历,第一个指针走到最后,第二个指针刚好是倒数k个节点
* @author Administrator
*
*/
public ListNode FindKthToTail(ListNode head,int k) {
if(head==null|k<=0){
return null;
}
ListNode first,second;
first=second=head;
for(int i=1;i<k;i++){
if(first.next!=null){
first=first.next;
}else{
return null;
}
}
while(first.next!=null){
first=first.next;
second=second.next;
}
return second;
}