# 22.链表中倒数第k个节点

## 题目

输入一个链表，输出该链表中倒数第k个节点。为了符合大多数人的习惯，本题从1开始计数，即链表的尾节点是倒数第1个节点。

例如，一个链表有 6 个节点，从头节点开始，它们的值依次是 1、2、3、4、5、6。这个链表的倒数第 3 个节点是值为 4 的节点。

示例：

```cpp
 给定一个链表: 1->2->3->4->5, 和 k = 2.

 返回链表 4->5.
 通过次数193,790提交次数246,166
```

来源：力扣（LeetCode）

链接：<https://leetcode-cn.com/problems/lian-biao-zhong-dao-shu-di-kge-jie-dian-lcof>

著作权归领扣网络所有。商业转载请联系官方授权，非商业转载请注明出处。

> [GitHub](https://github.com/RyukieSama/RyukiePlayground/blob/main/剑指Offer.playground/Pages/22.链表中倒数第k个节点.xcplaygroundpage/Contents.swift)

## 解法一：栈

```swift
func getKthFromEnd(_ head: ListNode?, _ k: Int) -> ListNode? {
    var node = head

    var temp: [ListNode] = []

    while let currentNode = node {
        temp.insert(currentNode, at: 0)
        if temp.count > k {
            temp.removeLast()
        }
        node = currentNode.next
    }

    return temp.last
}
```

## 解法二：差速双指针

```swift
 func getKthFromEnd(_ head: ListNode?, _ k: Int) -> ListNode? {
    var right: ListNode? = head, left: ListNode? = head

    // 移动到 第 k 个节点
    for _ in 0..<k-1 {
        right = right?.next
    }

    while let _ = right?.next {
        right = right?.next
        left = left?.next
    }

    return left
}
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://ryukiedev.gitbook.io/wiki/shu-ju-jie-gou-yu-suan-fa/jian-zhi-offerswift/22.-lian-biao-zhong-dao-shu-dikge-jie-dian.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
