# 25. Reverse Nodes in k-Group

#include<iostream>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};

class Solution {
public:
ListNode* reverseKGroup(ListNode* head, int k) {
ListNode *p,*L,*tmp,*q;
int length,i;
length=0;
while(p)
{
length++;
p=p->next;
}
L=(ListNode*)malloc(sizeof(struct ListNode));
L->next=NULL;//L是逆转链表
tmp=L;//tmp是临时链表用来存放逆转的k个元素
{
for(i=0;i<k;i++)
{
q->next=tmp->next;
tmp->next=q; //采用头插法逆转元素
}
while(tmp->next)//将tmp清空到最后一个节点好连接下面的k个元素
tmp=tmp->next;
length=length-k;
}
return L->next;
}
};
int main()
{
ListNode* L,*result,*p,*q;
int N,i,temp,k;
Solution solve;
cin>>N;
cin>>k;
L=(ListNode*)malloc(sizeof(struct ListNode));
L->next=NULL;
p=L;
for(i=0;i<N;i++)
{
cin>>temp;
q=(ListNode*)malloc(sizeof(struct ListNode));
q->val=temp;
q->next=NULL;
p->next=q;
p=q;
}
result=solve.reverseKGroup(L->next,k);
while(result)
{
cout<<result->val<<' ';
result=result->next;
}
return 0;
}

#include<iostream>
#include<stack>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};

class Solution {
public:
ListNode* reverseKGroup(ListNode* head, int k) {
stack<ListNode*> s;
ListNode *L,*start,*end,*q,*tmp;
int count;
L=(ListNode*)malloc(sizeof(ListNode));
L->next=NULL;
tmp=L;
end=start;
while(1)
{
count=k;
while(count&&end)//start和end之间隔了k个元素
{
count--;
s.push(end);
end=end->next;
}
if(!count)
{
while(!s.empty())//采用尾插法插入
{
q=s.top();
s.pop();
tmp->next=q;
tmp=q;
}
start=end;
end=start;
}
else
break;
}
tmp->next=start;
return L->next;
}
};
int main()
{
ListNode* L,*result,*p,*q;
int N,i,temp,k;
Solution solve;
cin>>N;
cin>>k;
L=(ListNode*)malloc(sizeof(struct ListNode));
L->next=NULL;
p=L;
for(i=0;i<N;i++)
{
cin>>temp;
q=(ListNode*)malloc(sizeof(struct ListNode));
q->val=temp;
q->next=NULL;
p->next=q;
p=q;
}
result=solve.reverseKGroup(L->next,k);
while(result)
{
cout<<result->val<<' ';
result=result->next;
}
return 0;
}

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

2015-05-11 19:55:08

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

2014-02-26 06:27:12

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

2015-06-08 20:00:42

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

2016-06-02 22:06:36

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

2017-09-05 09:00:36

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

2015-03-05 15:04:52

#### [leetcode] 25. Reverse Nodes in k-Group 解题报告

2016-01-08 10:51:18

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

2016-11-22 10:30:24

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

2014-12-17 17:01:26

#### ★★★25. Reverse Nodes in k-Group

2018-04-18 11:38:01