题目:输入一个链表,输出该链表中倒数第k个节点。
type Node struct {
val int
next *Node
}
func findKthTail(head *Node, k int) int {
if head == nil || k < 1 {
return -1
}
p := head
count := 0
for p != nil {
count++
p = p.next
}
if count < k {
return -1
}
front, tail := head, head
for i := 0; i < k; i++ {
front = front.next
}
for front != nil {
front = front.next
tail = tail.next
}
return tail.val
}