views:

111

answers:

2

I have problems swapping adjacent nodes in a linkedlist.

for ex: input : 1->2->3->4->5->null output: 2->1->4->3->5->null

bool swapAdjacent(node** head)
{

//1->2->3->4->null

//2->1->4->3->null
if(head==NULL)
return 0;
node* current  = *head;
*head = (*head)->next ;
node* prev = NULL;
cout<<"head val "<<(*head)->data <<endl;
node* temp;
while( current!=NULL&&current->next!=NULL)
{
   temp = current->next ;  //1s pointer points to 2
   current->next = temp->next ;    // 1s pointer point to 3
   temp ->next = current;   //2s pointer shud point to 1
   prev = current;
   current = current->next ;
   //cout<<"data " <<current->data <<endl;

   if(current!=NULL)
   prev->next = current->next ;



}

return 1;
}

My code is not working whenever there are odd no of nodes. How to fix this ?

+2  A: 

Why so complicated?

int swapAdjacent(node** head) {
  if (!*head || !(*head)->next)
    return 0;
  node* sw = (*head)->next;
  (*head)->next = sw->next;
  sw->next = *head;
  *head = sw;
  swapAdjacent(&(sw->next->next));
  return 1;
}

Edit: changed return value.

bitmask
@bitmask thank you very much. Its really simple.
brett
+1  A: 

I don't know what is wrong with your code, but I would approach it by showing the state the of list at each pass through the loop:

void printList(node* head)
{
    int cntr = 1;

    while (head != NULL)
    {
        printf("(Node: %d. Name: %s) --> ", cntr, head->name);
        head = head->next;
    }
}

For this, make sure each node has a name, set to "1", "2", etc. Then printout the state of the list on each pass, perhaps even each step! And you should see what's going wrong.

abelenky
the last odd element is missing
brett