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
1 /** 2 * Definition for singly-linked list. 3 * struct ListNode { 4 * int val; 5 * ListNode *next; 6 * ListNode(int x) : val(x), next(NULL) {} 7 * }; 8 */ 9 class Solution { 10 public: 11 ListNode *reverseKGroup(ListNode *head, int k) { 12 if (head == NULL) 13 return head; 14 ListNode *p,*q,*r; 15 int i = 0; 16 p = head; 17 while (p) 18 { 19 p = p->next; 20 i++; 21 } 22 if (k > i) 23 return head; 24 i = 1; 25 p = head; 26 q = p->next; 27 if (q) 28 r = q->next; 29 while (i < k && q) 30 { 31 q->next = p; 32 p = q; 33 q = r; 34 if (q) 35 r = q->next; 36 i++; 37 } 38 head->next = reverseKGroup(q,k); 39 head = p; 40 return head; 41 } 42 };