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&¤t->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 ?