1. Description
Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.
k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k then left-out nodes, in the end, should remain as it is.
You may not alter the values in the list’s nodes, only nodes themselves may be changed.
Follow-up: Can you solve the problem in O(1) extra memory space?
给你一个链表,每 k 个节点一组进行翻转,请你返回翻转后的链表。
k 是一个正整数,它的值小于或等于链表的长度。
如果节点总数不是 k 的整数倍,那么请将最后剩余的节点保持原有顺序。
进阶:
你可以设计一个只使用常数额外空间的算法来解决此问题吗?
你不能只是单纯的改变节点内部的值,而是需要实际进行节点交换。
![](https://img-blog.csdnimg.cn/20210715153409957.png)
![](https://img-blog.csdnimg.cn/20210715153457397.png)
2. Analysis
递归思考:
- 先反转
head
开头的前k个节点(图中k=2):
![](https://img-blog.csdnimg.cn/2021071515392441.png)
![](https://img-blog.csdnimg.cn/20210715154213716.png)
- 再将第
k+1
个节点作为head
递归调用reversekKGroup
函数
![](https://img-blog.csdnimg.cn/20210715154520376.png)
- 最后将上述两步的结果拼接起来
![](https://img-blog.csdnimg.cn/20210715154707140.png)
递归的边界条件为节点个数小于k个,按照题目要求保留此部分节点顺序
3. Code
根据分析,我们应该先实现反转一个区间内的元素,在这之前稍作简化,给定头节点,如何反转整个链表?
// 迭代反转以 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;
}
【反转以a为头节点的链表】实际就是【反转从a到null之间的节点】,故【反转从a到b的节点】只用将上述代码中的null
改为b
即可。
/** 反转区间 [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
函数,故完整答案为:
class Solution{
private ListNode reverse(ListNode a, ListNode b){
ListNode pre, cur, nxt;
pre = null; cur = a; nxt = a;
while (cur != b) {
nxt = cur.next;
cur.next = pre;
pre = cur;
cur = nxt;
}
// 返回反转后的头结点
return pre;
}
ListNode reverseKGroup(ListNode head, int k){
ListNode a, b;
a = b = head;
for(int i = 0; i < k; i++){
// 节点不足k个,不反转
if(b == null) return head;
b = b.next;
}
ListNode newHead = reverse(a, b);
a.next = reverseKGroup(b, k);
return newHead;
}
}
4. Summary
- 本题采用递归思想,将链表分为两部分,前k个节点和剩余部分。调用
reverse
函数对位于[a, b)之间的节点进行反转,递归调用reverseKGroup
对剩余部分链表进行反转,再将二者结果拼接在一起。 - 对
reverse
函数实现的思考有其巧妙之处:要实现【反转部分链表】先思考如何【反转整个链表】,实现后者后,根据二者差异——反转结束点为null
或是指定节点b
,对while循环稍作改动即可实现【反转[a,b]之间的链表】。