1

Possible Duplicate:
Reverse every k nodes of a linked list

Say the linked list is <1,3,6,4,8,9,0,2>. Calling reversek(3) would result in <6,3,1,9,8,4,2,0>. I have written the reverse function which may be used as a helper function in reversek. Here's my reverse function which reverses from a given starting point to a given ending point:

    void List::reverse(Node * & start, Node * & end)
    {
    Node *pter = start;
    while (pter != NULL) 
    {
         Node *tmp = pter->next;
         pter->next = pter->prev;
         pter->prev = tmp;
         if (tmp == NULL) 
         {
            endPoint = startPoint;
            startPoint = pter;
         }
       pter = tmp;
    }

I'm confused about how to implement reversek, any help is appreciated.

Community
  • 1
  • 1
SKLAK
  • 3,825
  • 9
  • 33
  • 57

1 Answers1

0

Try something like -

  1. Have 2 pointers (P1, P2) to linked list head element.
  2. One is used for traversing the list(P1). While the other(P2) is used for swapping the elements once the traversing point is reached 3rd node in the list.
  3. Now move both the pointers to 4th node. And again continue P1 traversing rest of the list.

Here you have to keep track of when every 3rd node is reached by P1. Here it is 3 for example, but it depends on function argument.

Mahesh
  • 34,573
  • 20
  • 89
  • 115