If I get the linked record enter as:
1->2->3->Four and Ok=1,num=2
The specified output for the given query is 4->3->2->1
Swapping of information isn’t allowed and I’m given head pointer, the worth of Ok, and num as arguments of the operate.
I get segmentation fault regardless of checking all nook circumstances already num>Ok,Ok==1,Ok==num,Ok<=num/2.
Right here num represents the no. of nodes in a linked record, Ok is an integer sort variable denoting the place of the node to be swapped.
MY APPROACH:
I’ve first traversed the entire linked record to get earlier node and present node tips that could each the Kth node from the tip and Kth node from the start as prevnode1,currnode1,prevnode2, and currnode2.
Then I’ve modified the subsequent pointers of each present nodes with the assistance of an arbitrary temp pointer.
Then I’ve utilized numerous circumstances for altering the subsequent pointers of earlier nodes.
Please take a look on my code
Node *swapkthnode(Node* head, int num, int Ok)
{
int flag=0;
Node *prevnode1=head,*currnode1,*currnode2,*temp=NULL,*prevnode2=NULL;
if(Ok>num)
return head;
if(num==(2*Ok-1))
return head;
currnode1=head;
int i=1;
whereas(currnode1!=NULL&&i<Ok)
{
prevnode1=currnode1;
currnode1=currnode1->subsequent;
i++;
}
i=1;
currnode2=head;
whereas(currnode2!=NULL&&i<num-Ok)
{
prevnode2=currnode2;
currnode2=currnode2->subsequent;
i++;
}
if(currnode1&&currnode1->subsequent==currnode2)
flag=1;
if(currnode1&&currnode2)
{
temp=currnode1->subsequent;
currnode1->subsequent=currnode2->subsequent;
currnode2->subsequent=temp;
}
if(prevnode1==NULL)
{
head=currnode2;
prevnode2->subsequent=currnode1;
}
if(prevnode2==NULL)
{
head=currnode1;
prevnode1->subsequent=currnode2;
}
if(flag==1)
{
currnode1->next->subsequent=currnode2;
}
if(prevnode1!=NULL&&prevnode2!=NULL)
{
prevnode2->subsequent=currnode1;
prevnode1->subsequent=currnode2;
}
return head;
// Your Code right here
}