# Hard-题目14：25. Reverse Nodes in k-Group

56人阅读 评论(0)

Given a linked list, reverse the nodes of a linked list k at a time and return its modified 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 nodes, only nodes itself may be changed.
Only constant memory is allowed.
For example,
For k = 2, you should return: 2->1->4->3->5
For k = 3, you should return: 3->2->1->4->5

class Solution {
public:
ListNode *reverseKGroup(ListNode *head, int k) {

// count k nodes
for (int i = 0; i < k; i++)
if (nextgp)
nextgp = nextgp->next;
else

// reverse
ListNode *prev = NULL, *cur = head, *next = NULL;
while (cur != nextgp) {
next = cur->next;
if (prev)
cur->next = prev;
else
cur->next = reverseKGroup(nextgp, k);
prev = cur;
cur = next;
}
return prev;
}
};

24ms,beats 41.82%，众数24ms,58.05%
Cmershen的碎碎念：

0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：56498次
• 积分：3205
• 等级：
• 排名：第10668名
• 原创：270篇
• 转载：53篇
• 译文：0篇
• 评论：7条
文章分类
最新评论