Niuke: BM8 The last k nodes in the linked list
Article directory
Question description
Problem solving ideas
The fast pointer moves k positions ahead of the slow pointer. In the linked list, the fast pointer and the slow pointer jump down at the same time. Until the fast pointer completes the traversal, the slow pointer at this time is the k-th node from the bottom.
Solution code
package main
import . "nc_tools"
/*
* type ListNode struct{
* Val int
* Next *ListNode
* }
*/
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param pHead ListNode类
* @param k int整型
* @return ListNode类
*/
func FindKthToTail( pHead *ListNode , k int ) *ListNode {
// write code here
if k == 0 {
return nil
}
fast := pHead
for k > 0 {
if fast == nil {
return nil
}
fast=fast.Next
k--
}
for fast!=nil {
fast, pHead = fast.Next, pHead.Next
}
return pHead
}