> For the complete documentation index, see [llms.txt](https://imhuay.gitbook.io/studies/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://imhuay.gitbook.io/studies/algorithms/problems/2022/03/niu-ke-0069-jian-dan-lian-biao-zhong-dao-shu-zui-houkge-jie-dian.md).

# 链表中倒数最后k个结点

![last modify](https://img.shields.io/static/v1?label=last%20modify\&message=2022-10-14%2014%3A59%3A33\&color=yellowgreen\&style=flat-square) [![](https://img.shields.io/static/v1?label=\&message=%E7%AE%80%E5%8D%95\&color=yellow\&style=flat-square)](https://imhuay.gitbook.io/studies/algorithms/problems/2022/03/pages/R5NyOzkn3qAZy7wCx1pS#简单) [![](https://img.shields.io/static/v1?label=\&message=%E7%89%9B%E5%AE%A2\&color=green\&style=flat-square)](https://imhuay.gitbook.io/studies/algorithms/problems/2022/03/pages/R5NyOzkn3qAZy7wCx1pS#牛客) [![](https://img.shields.io/static/v1?label=\&message=%E5%8F%8C%E6%8C%87%E9%92%88\&color=blue\&style=flat-square)](https://imhuay.gitbook.io/studies/algorithms/problems/2022/03/pages/R5NyOzkn3qAZy7wCx1pS#双指针)

> [链表中倒数最后k个结点\_牛客题霸\_牛客网](https://www.nowcoder.com/practice/886370fe658f41b498d40fb34ae76ff9)

**问题简述**

```
输入一个长度为 n 的链表，设链表中的元素的值为 ai ，返回该链表中倒数第k个节点。
如果该链表长度小于k，请返回一个长度为 0 的链表。
```

**思路1**

* 先计算链表长度 `L`，再重新走 `L-k` 步；

<details>

<summary><strong>Python</strong></summary>

```python
class Solution:
    def FindKthToTail(self , pHead: ListNode, k: int) -> ListNode:
        
        L = 0
        cur = pHead
        while cur:
            cur = cur.next
            L += 1
        
        cur = pHead
        d = L - k
        while d and cur:
            cur = cur.next
            d -= 1
        
        return cur
```

</details>

**思路2：快慢指针**

* 快指针先走 `k` 步；最后返回慢指针；

<details>

<summary><strong>Python</strong></summary>

```python
class Solution:
    def FindKthToTail(self , pHead: ListNode, k: int) -> ListNode:
        
        f, s = pHead, pHead
        # 快指针先走 k 步
        for _ in range(k):
            if not f:
                return f
            f = f.next
        
        while f:
            f = f.next
            s = s.next
        
        return s
```

</details>
