题目:找出单链表中倒数第K个结点.
核心代码:
func nthToLastNode(node:ListNode,k:Int) -> ListNode? {
if k <= 0 {
return nil
}
var p1:ListNode? = node
var p2:ListNode? = node
for _ in 0..<k - 1 {
if p2 == nil {
return nil
}
p2 = p2?.next
}
if p2 == nil {
return nil
}
while p2?.next != nil {
p1 = p1?.next
p2 = p2?.next
}
return p1
}
测试代码:
var nthNode:ListNode? = listNodeManger.nthToLastNode(node: listNodeManger.headNode!, k: 3)
if nthNode != nil {
print("FlyElephant--倒数的k个节点:\(nthNode!.value!)")
}