25. Reverse Nodes in k-Group
题目大意
Given the head of a linked list, reverse the nodes of the list k at a time, and return the 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.
中文释义
给定一个链表的头节点,每次反转 k 个节点,并返回修改后的链表。
k 是一个正整数,且小于或等于链表的长度。如果节点数不是 k 的倍数,则最后剩下的节点应保持原样。
你不能更改链表节点中的值,只能更改节点本身。
示例
Example 1:
Input: head = [1,2,3,4,5]
, k = 2
Output: [2,1,4,3,5]
Example 2:
Input: head = [1,2,3,4,5]
, k = 3
Output: [3,2,1,4,5]
限制条件
- 链表中的节点数为 n。
1 <= k <= n <= 5000
0 <= Node.val <= 1000
进阶问题
你能在 O(1) 额外内存空间中解决这个问题吗?
解题思路
方法
即在给定的单链表中每 k 个节点为一组进行反转。该方法使用迭代方式。
-
边界条