k个一组反转链表.md 9.0 KB
Newer Older
L
labuladong 已提交
1 2
# 如何k个一组反转链表

3

L
labuladong 已提交
4 5 6



7 8
<p align='center'>
<a href="https://github.com/labuladong/fucking-algorithm" target="view_window"><img alt="GitHub" src="https://img.shields.io/github/stars/labuladong/fucking-algorithm?label=Stars&style=flat-square&logo=GitHub"></a>
L
labuladong 已提交
9
<a href="https://appktavsiei5995.pc.xiaoe-tech.com/index" target="_blank"><img class="my_header_icon" src="https://img.shields.io/static/v1?label=精品课程&message=查看&color=pink&style=flat"></a>
10 11 12 13
<a href="https://www.zhihu.com/people/labuladong"><img src="https://img.shields.io/badge/%E7%9F%A5%E4%B9%8E-@labuladong-000000.svg?style=flat-square&logo=Zhihu"></a>
<a href="https://space.bilibili.com/14089380"><img src="https://img.shields.io/badge/B站-@labuladong-000000.svg?style=flat-square&logo=Bilibili"></a>
</p>

L
labuladong 已提交
14
![](https://labuladong.github.io/algo/images/souyisou1.png)
15

L
labuladong 已提交
16
**通知:[数据结构精品课 V1.8](https://aep.h5.xeknow.com/s/1XJHEO) 持续更新中。**
17 18


L
labuladong 已提交
19 20 21 22 23 24

读完本文,你不仅学会了算法套路,还可以顺便解决如下题目:

| LeetCode | 力扣 | 难度 |
| :----: | :----: | :----: |
| [25. Reverse Nodes in k-Group](https://leetcode.com/problems/reverse-nodes-in-k-group/) | [25. K 个一组翻转链表](https://leetcode.cn/problems/reverse-nodes-in-k-group/) | 🔴
25 26 27

**-----------**

L
labuladong 已提交
28 29
之前的文章「递归反转链表的一部分」讲了如何递归地反转一部分链表,有读者就问如何迭代地反转链表,这篇文章解决的问题也需要反转链表的函数,我们不妨就用迭代方式来解决。

L
labuladong 已提交
30
本文要解决力扣第 25 题「K 个一组翻转链表」,题目不难理解:
L
labuladong 已提交
31

L
labuladong 已提交
32
![](https://labuladong.github.io/algo/images/kgroup/title.png)
L
labuladong 已提交
33

L
labuladong 已提交
34
这个问题经常在面经中看到,而且力扣上难度是 Hard,它真的有那么难吗?
L
labuladong 已提交
35 36 37 38 39

对于基本数据结构的算法问题其实都不难,只要结合特点一点点拆解分析,一般都没啥难点。下面我们就来拆解一下这个问题。

### 一、分析问题

L
labuladong 已提交
40
首先,前文 [学习数据结构的框架思维](https://labuladong.github.io/article/fname.html?fname=学习数据结构和算法的高效方法) 提到过,链表是一种兼具递归和迭代性质的数据结构,认真思考一下可以发现**这个问题具有递归性质**
L
labuladong 已提交
41 42 43

什么叫递归性质?直接上图理解,比如说我们对这个链表调用 `reverseKGroup(head, 2)`,即以 2 个节点为一组反转链表:

L
labuladong 已提交
44
![](https://labuladong.github.io/algo/images/kgroup/1.jpg)
L
labuladong 已提交
45 46 47

如果我设法把前 2 个节点反转,那么后面的那些节点怎么处理?后面的这些节点也是一条链表,而且规模(长度)比原来这条链表小,这就叫**子问题**

L
labuladong 已提交
48
![](https://labuladong.github.io/algo/images/kgroup/2.jpg)
L
labuladong 已提交
49

L
labuladong 已提交
50
我们可以把原先的 `head` 指针移动到后面这一段链表的开头,然后继续递归调用 `reverseKGroup(head, 2)`,因为子问题(后面这部分链表)和原问题(整条链表)的结构完全相同,这就是所谓的递归性质。
L
labuladong 已提交
51 52 53 54 55

发现了递归性质,就可以得到大致的算法流程:

**1、先反转以 `head` 开头的 `k` 个元素**

L
labuladong 已提交
56
![](https://labuladong.github.io/algo/images/kgroup/3.jpg)
L
labuladong 已提交
57 58 59

**2、将第 `k + 1` 个元素作为 `head` 递归调用 `reverseKGroup` 函数**

L
labuladong 已提交
60
![](https://labuladong.github.io/algo/images/kgroup/4.jpg)
L
labuladong 已提交
61 62 63

**3、将上述两个过程的结果连接起来**

L
labuladong 已提交
64
![](https://labuladong.github.io/algo/images/kgroup/5.jpg)
L
labuladong 已提交
65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91

整体思路就是这样了,最后一点值得注意的是,递归函数都有个 base case,对于这个问题是什么呢?

题目说了,如果最后的元素不足 `k` 个,就保持不变。这就是 base case,待会会在代码里体现。

### 二、代码实现

首先,我们要实现一个 `reverse` 函数反转一个区间之内的元素。在此之前我们再简化一下,给定链表头结点,如何反转整个链表?

```java
// 反转以 a 为头结点的链表
ListNode reverse(ListNode a) {
    ListNode pre, cur, nxt;
    pre = null; cur = a; nxt = a;
    while (cur != null) {
        nxt = cur.next;
        // 逐个结点反转
        cur.next = pre;
        // 更新指针位置
        pre = cur;
        cur = nxt;
    }
    // 返回反转后的头结点
    return pre;
}
```

L
labuladong 已提交
92 93 94
算法执行的过程如下 GIF 所示::

![](https://labuladong.github.io/algo/images/kgroup/8.gif)
L
labuladong 已提交
95 96 97 98 99 100

这次使用迭代思路来实现的,借助动画理解应该很容易。

「反转以 `a` 为头结点的链表」其实就是「反转 `a` 到 null 之间的结点」,那么如果让你「反转 `a``b` 之间的结点」,你会不会?

只要更改函数签名,并把上面的代码中 `null` 改成 `b` 即可:
101

L
labuladong 已提交
102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119
```java
/** 反转区间 [a, b) 的元素,注意是左闭右开 */
ListNode reverse(ListNode a, ListNode b) {
    ListNode pre, cur, nxt;
    pre = null; cur = a; nxt = a;
    // while 终止的条件改一下就行了
    while (cur != b) {
        nxt = cur.next;
        cur.next = pre;
        pre = cur;
        cur = nxt;
    }
    // 返回反转后的头结点
    return pre;
}
```

现在我们迭代实现了反转部分链表的功能,接下来就按照之前的逻辑编写 `reverseKGroup` 函数即可:
120

L
labuladong 已提交
121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138
```java
ListNode reverseKGroup(ListNode head, int k) {
    if (head == null) return null;
    // 区间 [a, b) 包含 k 个待反转元素
    ListNode a, b;
    a = b = head;
    for (int i = 0; i < k; i++) {
        // 不足 k 个,不需要反转,base case
        if (b == null) return head;
        b = b.next;
    }
    // 反转前 k 个元素
    ListNode newHead = reverse(a, b);
    // 递归反转后续链表并连接起来
    a.next = reverseKGroup(b, k);
    return newHead;
}
```
139

L
labuladong 已提交
140 141
解释一下 `for` 循环之后的几句代码,注意 `reverse` 函数是反转区间 `[a, b)`,所以情形是这样的:

L
labuladong 已提交
142
![](https://labuladong.github.io/algo/images/kgroup/6.jpg)
L
labuladong 已提交
143 144 145

递归部分就不展开了,整个函数递归完成之后就是这个结果,完全符合题意:

L
labuladong 已提交
146
![](https://labuladong.github.io/algo/images/kgroup/7.jpg)
L
labuladong 已提交
147 148 149 150 151

### 三、最后说两句

从阅读量上看,基本数据结构相关的算法文章看的人都不多,我想说这是要吃亏的。

L
labuladong 已提交
152
大家喜欢看动态规划相关的问题,可能因为面试很常见,但就我个人理解,很多算法思想都是源于数据结构的。我们公众号的成名之作之一,[学习数据结构的框架思维](https://labuladong.github.io/article/fname.html?fname=学习数据结构和算法的高效方法) 就提过,什么动规、回溯、分治算法,其实都是树的遍历,树这种结构它不就是个多叉链表吗?你能处理基本数据结构的问题,解决一般的算法问题应该也不会太费事。
L
labuladong 已提交
153

L
labuladong 已提交
154 155
那么如何分解问题、发现递归性质呢?这个只能多练习,也许后续可以专门写一篇文章来探讨一下,本文就到此为止吧,希望对大家有帮助!

L
labuladong 已提交
156 157
> 最后打个广告,我亲自制作了一门 [数据结构精品课](https://aep.h5.xeknow.com/s/1XJHEO),以视频课为主,手把手带你实现常用的数据结构及相关算法,旨在帮助算法基础较为薄弱的读者深入理解常用数据结构的底层原理,在算法学习中少走弯路。

158
**_____________**
K
KAGAWA317 已提交
159

L
labuladong 已提交
160
**《labuladong 的算法小抄》已经出版,关注公众号查看详情;后台回复关键词「进群」可加入算法群;回复「PDF」可获取精华文章 PDF**
L
labuladong 已提交
161

L
labuladong 已提交
162
![](https://labuladong.github.io/algo/images/souyisou2.png)
L
labuladong 已提交
163

L
labuladong 已提交
164

B
brucecat 已提交
165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241
======其他语言代码======

[25.K个一组翻转链表](https://leetcode-cn.com/problems/reverse-nodes-in-k-group)

### javascript

```js
/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */


// 示例一:反转以a为头结点的链表
let reverse = function (a) {
    let pre, cur, nxt;
    pre = null;
    cur = a;
    nxt = a;
    while (cur != null) {
        nxt = cur.next;
        // 逐个结点反转
        cur.next = pre;
        // 更新指针位置
        pre = cur;
        cur = nxt;
    }
    // 返回反转后的头结点
    return pre;
}

/** 反转区间 [a, b) 的元素,注意是左闭右开 */
let reverse = (a, b) => {
    let pre, cur, nxt;
    pre = null;
    cur = a;
    nxt = a;
    // while 终止的条件改一下就行了
    while (cur !== b) {
        nxt = cur.next;
        cur.next = pre;
        pre = cur;
        cur = nxt;
    }
    // 返回反转后的头结点
    return pre;
}


/**
 * @param {ListNode} head
 * @param {number} k
 * @return {ListNode}
 */
let reverseKGroup = (head, k) => {
    if (head == null) return null;
    // 区间 [a, b) 包含 k 个待反转元素
    let a, b;
    a = b = head;
    for (let i = 0; i < k; i++) {
        // 不足k个,不需反转,base case
        if(b==null) return head;
        b = b.next;
    }

    // 反转前k个元素
    let newHead = reverse(a,b);

    // 递归反转后续链表并连接起来
    a.next = reverseKGroup(b,k);
    return newHead;
}
```