# 【Leetcode】Reverse Nodes in k-Group

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,
Given this linked list: 1->2->3->4->5

For k = 2, you should return: 2->1->4->3->5

For k = 3, you should return: 3->2->1->4->5

2）若不足k个结点，则将反转后的结点重新反转，其中只需要先把cur和post指针调换即可，其余处理细节和1）相同。

3）处理完反转后，有以下几个步骤用来连接后续结点。

1.当前结点temp设为pre->next；

2.将pre->next设为cur；

3.将temp->next设为post；

4.将pre设为temp；

5.将cur设为post。

class Solution {
public:
ListNode *reverseKGroup(ListNode *head, int k) {
ListNode *safeG=new ListNode(-1);
while(cur!=NULL)
{
post=cur->next;
int i=0;
while(i<k-1&&post!=NULL)
{
ListNode *temp=post->next;
post->next=cur;
cur=post;
post=temp;
i++;
}
if(i!=k-1)
{
int m=0;
//交换cur,post结点
ListNode *temp=post;
post=cur;
cur=temp;
while(m<i)
{
temp=post->next;
post->next=cur;
cur=post;
post=temp;
m++;
}
break;
}
ListNode *temp=pre->next;
pre->next=cur;
temp->next=post;
pre=temp;
cur=post;
}
delete safeG;
}
};

## leetcode之Partition List，Reverse Nodes in k-Group

Partition List Given a linked list and a value x, partition it such that all nodes less than x com...

## leetcode25---Reverse Nodes in k-Group

• will130
• 2015年12月20日 23:59
• 281

## LeetCode 25. Reverse Nodes in k-Group

Given a linked list, reverse the nodes of a linked list k at a time and return its modified list. k...

## [Leetcode] Reverse Nodes in k-Group (Java)

Given a linked list, reverse the nodes of a linked list k at a time and return its modified list. I...

## [LeetCode]25.Reverse Nodes in k-Group

【题目】 Given a linked list, reverse the nodes of a linked list k at a time and return its modified l...

## Leetcode25 Reverse Nodes in k-Group

Reverse Nodes in k-Group My Submissions Question Solution Given a linked list, reverse the nod...

## [leetcode] 25. Reverse Nodes in k-Group

Given a linked list, reverse the nodes of a linked list k at a time and return its modified list. I...

举报原因： 您举报文章：【Leetcode】Reverse Nodes in k-Group 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)