# 一.问题描述

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

# 二.我的解题思路

/**
* struct ListNode {
*     int val;
*     ListNode *next;
*     ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* reverseKGroup(ListNode* head, int k) {
ListNode* curr,* next,* tmp;
ListNode* st,* end;
int cnt=0;
if(curr==NULL) return NULL;
while(curr!=NULL){
cnt++;
if(cnt==k)
break;
curr=curr->next;
}   //judge if there exists k nodes
if(cnt==k){ //if exists
while(cnt<k){
next=end->next;
tmp=next->next;
next->next=st;
end->next=tmp;
st=next;
cnt++;
}
if(end->next==NULL)
return st;
end->next=reverseKGroup(end->next,k);
return st;
}

}
};

#### LeetCode 25 Reverse Nodes in k-Group (C,C++,Java,Python)

2015-05-11 19:55:08

#### （Java）LeetCode-25. Reverse Nodes in k-Group

2016-06-02 22:06:36

#### [LeetCode] 025. Reverse Nodes in k-Group (Hard) (C++/Java)

2015-03-05 15:04:52

#### 【Leetcode】【python】Reverse Nodes in k-Group

2017-09-05 09:00:36

#### 【LeetCode】Reverse Nodes in k-Group 解题报告

2014-12-17 17:01:26

#### LeetCode 25: Reverse Nodes in k-Group

2015-06-08 20:00:42

#### Reverse Nodes in k-Group -- LeetCode

2014-02-26 06:27:12

#### 【LeetCode-面试算法经典-Java实现】【025-Reverse Nodes in k-Group（单链表中k个结点一组进行反转）】

2015-07-24 06:58:08

#### LeetCode | Reverse Nodes in k-Group（k个结点一组翻转链表）

2014-08-17 16:50:46

#### [leetcode]Reverse Nodes in k-Group 反转以k个节点为一组的链表

2014-08-04 07:22:12

## 不良信息举报

【Leetcode】之Reverse Nodes in k-Group