Monday, June 15, 2015

Reverse a Linked List in groups of given size

Problem: Given a linked list, write a function to reverse every k nodes.

Solution: Tweak the reverse method to get the desired result.

Implementation:

//Public interface
void List::reverseK(int k)
{
if(!head || k == 0)
return;

head = reverseK(head, k);
}

//Actual Implementation
List::ListNode* List::reverseK(List::ListNode *node, int k)
{
ListNode *curr = node;
ListNode *next = 0, *prev = 0;
int count = 1;
while(curr && count <= k)
{
next = curr->next;
curr->next = prev;
prev = curr;
curr = next;
++count;
}

if(next)
node->next = reverseK(next, k);
return prev;
}

Complexity: O(n)

No comments:

Post a Comment