K 个一组翻转链表
题意给你链表的头节点 head ,每 k 个节点一组进行翻转,请你返回修改后的链表。
k 是一个正整数,它的值小于或等于链表的长度。如果节点总数不是 k 的整数倍,那么请将最后剩余的节点保持原有顺序。
你不能只是单纯的改变节点内部的值,而是需要实际进行节点交换。
示例:
思路输入:head = [1,2,3,4,5], k = 2
输出:[2,1,4,3,5]
- 先实现两个函数,getGroupEnd 和 reverse,前一个函数根据开始起点start和间隔k,返回一组节点的尾部节点end;后一个函数实现对本组的链表的翻转,并将start的下一个节点指向end;
- 判断链表能否凑够第一组,若凑不够,直接返回head;若第一组凑齐了,则对第一组执行reverse操作,然而定义改组节点翻转完成后的尾部节点 lastEnd = start,若lastEnd不为空,循环执行后续每组链表。
Python
class ReverseKGroup:
"""
K 个一组翻转链表
"""
def solution(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:
def getKGroupEnd(s, k):
k -= 1
while k != 0 and s:
s = s.next
k -= 1
return s
def reverse(start, end):
end = end.next
pre, next = None, None
cur = start
while cur != end:
next = cur.next
cur.next = pre
pre = cur
cur = next
start.next = end
start = head
end = getKGroupEnd(start, k)
# 凑不够一组,直接返回head
if not end:
return head
# 第一组凑齐了,最终返回的head指向第一组的尾节点
head = end
reverse(start, end)
# 上一组的结尾节点
lastEnd = start
while lastEnd.next:
start = lastEnd.next
end = getKGroupEnd(start, k)
if not end:
return head
reverse(start, end)
lastEnd.next = end
# 这一组的结尾节点
lastEnd = start
return head
Java
public class ReverseNodesInKGroup {
// 不要提交这个类
public static class ListNode {
public int val;
public ListNode next;
}
public static ListNode reverseKGroup(ListNode head, int k) {
ListNode start = head;
ListNode end = getKGroupEnd(start, k);
if (end == null) {
return head;
}
// 第一组凑齐了!
head = end;
reverse(start, end);
// 上一组的结尾节点
ListNode lastEnd = start;
while (lastEnd.next != null) {
start = lastEnd.next;
end = getKGroupEnd(start, k);
if (end == null) {
return head;
}
reverse(start, end);
lastEnd.next = end;
lastEnd = start;
}
return head;
}
public static ListNode getKGroupEnd(ListNode start, int k) {
while (--k != 0 && start != null) {
start = start.next;
}
return start;
}
public static void reverse(ListNode start, ListNode end) {
end = end.next;
ListNode pre = null;
ListNode cur = start;
ListNode next = null;
while (cur != end) {
next = cur.next;
cur.next = pre;
pre = cur;
cur = next;
}
start.next = end;
}
}



