Interview Questions

269. Given a linked list of numbers. Swap every 2 adjacent links.......

Microsoft Interview Questions and Answers


(Continued from previous question...)

269. Given a linked list of numbers. Swap every 2 adjacent links.......

Question:

Given a linked list of numbers. Swap every 2 adjacent links. For eg if a linked list given to you is- a->b->c->d->e->f O/p expected- b->a->d->c->f->e Every 2 alternate links have to be swapped. Pls note that values stored in the link list have to remain at their previous locations only. Values are not to be swapped. Only links are to be swapped.


maybe an answer:


At point of time the situation is like prev->a->b->something
Node swapAdjacentNodes(Node root)
{ Node prev=NULL;
Node n=root;Node a,b;
while(n!=NULL &&n->next!=NULL)
{ a=n;
b=n->next;
if(prev!=NULL)
{ prev->next=b;
}
else
{ root=b;
}
a->next=b->next;
b->next=a;
prev=a;
n=a->next;

}
return root;
}

(Continued on next question...)

Other Interview Questions