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->5For k = 2, you should return: 2->1->4->3->5For k = 3, you should return: 3->2->1->4->51 /** 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(k <= 1) return head;13 int reverseTimes = getLength(head) / k;14 ListNode dummy(0);15 dummy.next = head;16 ListNode* pre = &dummy;17 ListNode* cur = pre->next;18 while(reverseTimes--) {19 for(int i = 0; i < k - 1; i++) {20 ListNode* move = cur->next;21 cur->next = move->next;22 move->next = pre->next;23 pre->next = move;24 }25 pre = cur;26 cur = pre->next;27 }28 return dummy.next;29 }30 31 int getLength(ListNode *head) 32 {33 int length = 0;34 while(head) {35 length++;36 head = head->next;37 }38 return length;39 }40 };