Link: https://leetcode.com/problems/reverse-nodes-in-k-group/
Problem description:
Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.
k is a positive integer and is less than or equal to the length of the linked 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 list's nodes, only nodes themselves may be changed.
e.g. Input: head = [1,2,3,4,5], k = 3 Output: [3,2,1,4,5]
My solution:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* reverseKGroup(ListNode* head, int k) {
ListNode** subHead = &head;
int i = 0;
for (ListNode* subTail = head; subTail != NULL; subTail = subTail->next) {
if ((i+1) % k == 0) {
ListNode* temp = subTail->next;
reverse(subHead, &subTail);
subTail->next = temp;
subHead = &(subTail->next);
}
i++;
}
return head;
}
void reverse(ListNode** subHead, ListNode** subTail) {
if (*subHead==NULL) return;
ListNode* itHead = *subHead;
ListNode* prev = NULL;
ListNode* next = NULL;
ListNode* end = (*subTail)->next;
while (itHead != end) {
next = itHead->next;
itHead->next = prev;
prev = itHead;
itHead = next;
}
std::swap(*subHead, *subTail);
}
};
This solution was accepted and seemed to do quite well in both space and time. I'm interested in how it can be optimized further, how it can be made more readable, more elegant, or better express good design principles. Note that the data definition and the signature ListNode* reverseKGroup(ListNode* head, int k)
is enforced by the question. Feel free to comment on anything you'd like though.