Friday, January 29, 2021

Swap nodes withoud swapping data

Approach: 

1. First, we will search the nodes x,y. 

2. If they are not present in the linked list, do nothing.

3. While searching for x and y keep track of the current and previous pointers.

4. First change the next of the previous pointer and then change the next of the current pointer.

Code:

Class node{}

void swapnode(node** head_ref, int x, int y)

{

//do nothing if both are same

if (x==y) return 0; 


//search for X and keep track of previous and current pointer

node *prevx= NULL, *currx= *head_ref;

while(currx && currx->data !=x)

{

prevx=currx; currx= currx->next;

}


//search for Y and keep track of the previous and current pointer

node *prevy=NULL, *curry=*head_ref;

while(prevy && curry->data)

{

 prevy= curry; curry= curry->next;

}


//if both X Y  are absent do nothing

if(currx==NULL || curry==NULL ) return;


//if x is not head of list

if(prevx!= NULL) prevx->curry;

else  *head_ref =curry; //make y as newhead



//if y is not head of list

if(prevy!=NULL) prevy->next= currx; 

else  *head_ref = currx;

}


//swap next pointers

node *temp = curry->next;

curry->next= currx->next;

currx->next= temp;

}


void push(node** head_ref, int new_data){}


void printlist(node* head) {} 


int main() {}

__________________________

A little optimization

void swap(node *& a, node *& b)

{ node *temp= a; a=b; b= temp;

}


void swapnode(node **head_ref, int x, int y)

{ if(x==y) return;


//search x,y and store their pointers in a and b

while(*head_ref)

{

if((*head_ref)->data==x){ a=head_ref;}

else if((*head_ref)->data==y) {b= head_ref;}

head_ref = &((*head_ref)->next);

} //while ends


//if a, b found, swap current and next pointer of these

if(a && b) 

   swap(*a, *b); 

swa(((*a)->next), ((*b)->next));

}

}


int main() {}



0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home