官方链接
https://leetcode-cn.com/problems/reverse-nodes-in-k-group/
给你一个链表,每 k 个节点一组进行翻转,请你返回翻转后的链表。
k 是一个正整数,它的值小于或等于链表的长度。
如果节点总数不是 k 的整数倍,那么请将最后剩余的节点保持原有顺序。
示例 :
给定这个链表:1->2->3->4->5
当 k = 2 时,应当返回: 2->1->4->3->5
当 k = 3 时,应当返回: 3->2->1->4->5
说明 :
你的算法只能使用常数的额外空间。
你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。
解法一
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode reverseKGroup(ListNode head, int k) {
ListNode dummy = new ListNode(-1);
dummy.next = head;
ListNode pre = dummy, end = dummy;
while (end != null && end.next != null) {
for (int i = 0; i < k; i++) {
if (end == null) break;
end = end.next;
}
if (end == null) break;
ListNode start = pre.next;
ListNode next = end.next;
end.next = null;
pre.next = reverse(start);
start.next = next;
pre = start;
end = pre;
}
return dummy.next;
}
private ListNode reverse(ListNode head) {
ListNode prepre = null, pre = null;
while (head != null) {
pre = head;
head = head.next;
pre.next = prepre;
prepre = pre;
}
return pre;
}
}
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def reverseKGroup(self, head: ListNode, k: int) -> ListNode:
dummy = ListNode(-1)
dummy.next = head
pre = end = dummy
while end and end.next:
for i in range(k):
if end:
end = end.next
else:
break
if not end:
break
start = pre.next
nex = end.next
end.next = None
pre.next = self.reverse(start)
start.next = nex
pre = start
end = pre
return dummy.next
def reverse(self, head: ListNode):
pre = None
while head:
head.next, head, pre = pre, head.next, head
return pre
字节变种
给定单链表的头结点 head,实现一个调整链表的函数,从链表尾部开始,以 K 个结点为一组进行逆序翻转,头部剩余结点不足一组时,不需要翻转。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
private ListNode reverseLastKGroup(ListNode head, int k) {
int length = ListLength(head);
int offset = length % k;
if (offset == 0) return reverseKGroup(head, k);
ListNode pre = new ListNode(-1);
pre.next = head;
for (int i = 0; i < offset; i++) {
pre = pre.next;
}
pre = reverseKGroup(pre.next, k);
return head;
}
private int ListLength(ListNode head) {
int count = 0;
while (head != null) {
head = head.next;
count++;
}
return count;
}
private ListNode reverseKGroup(ListNode head, int k) {
ListNode dummy = new ListNode(-1);
dummy.next = head;
ListNode pre = dummy, end = dummy;
while (end != null && end.next != null) {
for (int i = 0; i < k; i++) {
if (end == null) break;
end = end.next;
}
if (end == null) break;
ListNode start = pre.next;
ListNode next = end.next;
end.next = null;
pre.next = reverse(start);
start.next = next;
pre = start;
end = pre;
}
return dummy.next;
}
private ListNode reverse(ListNode head) {
ListNode prepre = null, pre = null;
while (head != null) {
pre = head;
head = head.next;
pre.next = prepre;
prepre = pre;
}
return pre;
}
}