public class E22FindKthNodeFromTail {
//链表中倒数第k个节点
private class ListNode{
int value;
ListNode nextNode;
}
public static ListNode findKthFromTail(ListNode head, int k){
if (head == null || k <= 0)
return null;
//指针ahead先行k-1步
ListNode ahead = head;
ListNode behind = null;
for (int i = 0; i < k - 1; i ++){
if (ahead == null)
return null;
ahead = ahead.nextNode;
}
//同时前进直至ahead到达末尾
behind = head;
while(ahead.nextNode != null){
behind = behind.nextNode;
ahead = ahead.nextNode;
}
return behind;
}
}
链表中倒数第k个节点(Java实现)
最新推荐文章于 2022-06-30 17:07:43 发布
本文介绍了一种寻找链表中倒数第K个节点的高效算法。通过两个指针,一个先走K-1步,然后两者同时移动直到前指针到达链表尾部,此时后指针所指向的即为所求节点。
543

被折叠的 条评论
为什么被折叠?



