Node* swapNode(Node* head , int x , int y )
{
if(x == y)
return ;
Node* prevX = NULL , *currX = head, *currY = head , *prevY = NULL ;
//find xth and yth node
for(int i = 0 ; i < x ; ++i)
{
prevX = currX ;
currX = currX->next;
}
for(int i = 0 ; i < y ; ++i)
{
prevY = currY ;
currY = currY->next;
}
if( currX == NULL || currY == NULL )
reutrn;
//doesnt matter x is smaller or bigger then y
//change head ptr
if(prevX != NULL )
prevX -> next = currY;
else
head = currY;
if(prevY != NULL )
prevY ->next = currX;
else
head = currX;
//swap next pointers
Node* temp = currX->next;
currX->next = currY->next;
currY->next = temp;
return head;
}
No comments:
Post a Comment