/**
* 两个指针,一个先走k-1步,然后两个同时向后移动,当提前走的指针移动到链表尾部时,落后的那个指针正好是要找的节点
* @param root
* @param k
* @return
*/
public static ListNode findKthTotail(ListNode root,int k){
if(root==null || k<=0){
return null;
}
ListNode ahead = root;
ListNode behind = root;
for(int i=0; i<k-1; i++){
if(ahead.getNext() != null){
ahead = ahead.getNext();
} else{
return null;
}
}
while(ahead.getNext() != null){
ahead = ahead.getNext();
behind = behind.getNext();
}
return behind;
}
Java-找出单链表的倒数第k结点
最新推荐文章于 2019-04-16 16:10:00 发布