Tuesday, December 18, 2012
Swap alternate nodes in a singly linked list
The concept is very easy . But you need to handle all test cases. One of the important test case is before assigning the odd_node->link to even_node , you should check whether it is NULL or NOT . Otherwise it will cause Segmentation Fault .
Code:
struct node* swap_alternate_nodes(struct node* head)
{
struct node* odd_node,even_node,temp;
if(head==NULL)
return NULL;
odd_node=head;
even_node=head->link;
if(head->link!=NULL)
head=head->link;
while(odd_node && even_node)
{
temp=even_node->link;
even_node->link=odd_node;
odd_node->link=temp;
odd_node=temp;
if(odd_node!=NULL)
even_node=odd_node->link;
}
return head;
}
Input : 1->2->3->4->5->NULL
Output: 2->1->4->3->->5->NULL
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment