http://www.geeksforgeeks.org/reverse-a-list-in-groups-of-given-size/
1 #include <iostream> 2 #include <vector> 3 #include <algorithm> 4 #include <queue> 5 #include <stack> 6 #include <string> 7 #include <fstream> 8 #include <map> 9 #include <set> 10 using namespace std; 11 12 struct node { 13 int data; 14 node *next; 15 node() : data(0), next(NULL) { } 16 node(int d) : data(d), next(NULL) { } 17 }; 18 19 void push(node* &head, int k) { 20 node *new_node = new node(k); 21 new_node->next = head; 22 head = new_node; 23 } 24 25 node* reverselist(node *&head, int k) { 26 node *cur = head; 27 node *pre = NULL; 28 node *next; 29 int c = 0; 30 while (cur && c < k) { 31 next = cur->next; 32 cur->next = pre; 33 pre = cur; 34 cur = next; 35 c++; 36 } 37 if (next) head->next = reverselist(next, k); 38 return pre; 39 } 40 41 void print(node *head) { 42 while (head) { 43 cout << head->data << " "; 44 head = head->next; 45 } 46 } 47 48 int main() { 49 node *head = NULL; 50 push(head, 8); 51 push(head, 7); 52 push(head, 6); 53 push(head, 5); 54 push(head, 4); 55 push(head, 3); 56 push(head, 2); 57 push(head, 1); 58 head = reverselist(head, 3); 59 print(head); 60 return 0; 61 }