Monday, February 16, 2015

Amazon Question: Reverse a Linked List in groups of given size

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

Implementation:

void List::reverseK(int k)
{
     if(head)
             head = reverseK(head, k);
}

Node* List::reverseK(Node *node, int k)
{
     Node *curr = node, *next = 0, *prev = 0;
     int count = 0;
     while(curr && (count < k))
     {
                 next = curr->next;
                 curr->next = prev;
                 prev = curr;
                 curr = next;
                 ++count;
     }
   
     if(next)
             node->next = reverseK(next, k);
     return prev;
}

No comments:

Post a Comment