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.
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
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: /** * @param head a ListNode * @param k an integer * @return a ListNode */ ListNode *reverseKGroup(ListNode *head, int k) { // Write your code here if (head == NULL || k == 1) { return head; } ListNode *p = head; ListNode *tail = NULL; ListNode *result = head; while (true) { int steps = k - 1; ListNode *oldHead = p; while (steps > 0 && p != NULL && p->next != NULL) { p = p->next; steps--; } if (steps > 0) { break; } ListNode *nextHead = p->next; p->next = NULL; ListNode *newHead = reverseList(oldHead); if (tail != NULL) { tail->next = newHead; } else { result = newHead; } tail = newHead; for (int i = k-1; i > 0; i--) { tail = tail->next; } tail->next = nextHead; p = nextHead; } return result; } private: ListNode* reverseList(ListNode *head) { ListNode *r = head->next; ListNode *p = head; ListNode *q = NULL; while (r != NULL) { p->next = q; q = p; p = r; r = r->next; } p->next = q; return p; } };