1. 本题知识点
链表
2. 题目描述
给你一个链表,每 k 个节点一组进行翻转,请你返回翻转后的链表。
k 是一个正整数,它的值小于或等于链表的长度。
如果节点总数不是 k 的整数倍,那么请将最后剩余的节点保持原有顺序。
进阶:
- 你可以设计一个只使用常数额外空间的算法来解决此问题吗?
- 你不能只是单纯的改变节点内部的值,而是需要实际进行节点交换。
输入:head = [1,2,3,4,5], k = 2
输出:[2,1,4,3,5]
输入:head = [1,2,3,4,5], k = 3
输出:[3,2,1,4,5]
3. 解题思路
- 选取 K 个要翻转的结点,不够 K 个则直接返回头结点
- 将这 K 个结点交给翻转函数
- 递归以上过程
4. 代码
public class Solution {
public ListNode reverseKGroup(ListNode head, int k) {
if (head == null || head.next == null) {
return head;
}
ListNode tail = head;
// 选取 K 个要翻转的结点,不够 K 个则直接返回头结点
for (int i = 0; i < k; i++) {
if (tail == null) {
return head;
}
tail = tail.next;
}
// 返回翻转后头结点
ListNode newHead = reverse(head, tail); // [) 左闭右开,head 变为链表尾部,tail 不变
head.next = reverseKGroup(tail, k);
return newHead;
}
public ListNode reverse(ListNode head, ListNode tail) {
ListNode pre = null, next = null;
while (head != tail) {
next = head.next;
head.next = pre;
pre = head;
head = next;
}
return pre;
}
}