题目描述:给你一个链表,每 k 个节点一组进行翻转,请你返回翻转后的链表。k 是一个正整数,它的值小于或等于链表的长度。如果节点总数不是 k 的整数倍,那么请将最后剩余的节点保持原有顺序。你可以设计一个只使用常数额外空间的算法来解决此问题吗?你不能只是单纯的改变节点内部的值,而是需要实际进行节点交换。
原题介绍
示例一
digraph leetcode_92_1 {
bgcolor="#f7f7f7"
rankdir=LR
subgraph cluster_name {
subgraph cluster_1 {
n0 [label="1" shape=circle,color=blue,fillcolor=lightblue,style=filled]
n1 [label="2" shape=circle,color=blue,fillcolor=lightblue,style=filled]
n2 [label="3" shape=circle,color=yellow,fillcolor=lightyellow,style=filled]
n3 [label="4" shape=circle,color=yellow,fillcolor=lightyellow,style=filled]
n4 [label="5" shape=circle,color=black,fillcolor=white,style=filled]
rank=same;
n0 -> n1 -> n2 -> n3 -> n4
style=invis
}
subgraph cluster_2 {
r0 [label="2" shape=circle,color=blue,fillcolor=lightblue,style=filled]
r1 [label="1" shape=circle,color=blue,fillcolor=lightblue,style=filled]
r2 [label="4" shape=circle,color=yellow,fillcolor=lightyellow,style=filled]
r3 [label="3" shape=circle,color=yellow,fillcolor=lightyellow,style=filled]
r4 [label="5" shape=circle,color=black,fillcolor=white,style=filled]
rank=same;
r0 -> r1 -> r2 -> r3 -> r4
style=invis
}
n2 -> r2[constraint=false,color="red",pad=30]
}
label=<<B>图 1.1 示例一</B>>
}
1 | 输入:head = [1,2,3,4,5], k = 2 |
代码实现
递归实现
1 | public class Solution { |