Hi there,
I am practicing making a double linked list. And I make a function to swap two nodes of double linked list but there's a problem in setting temporary variable to keep node's original link address...
To switch two node pointers, object1 and object2, I made another two local node pointers, temp1 and temp2, to store object1 and object2's original addresses.
But in the middle of process when I changed object's link, temp1 and temp2's addresses are also changed..
I don't want to lose the address that I set first in temp1 and temp2..
Can anybody help me to figure out how I can fix it or
show me the right-working swap function working by handling links in double linked list?
it's my struct for double linked list.
And bellow is swap function that I made..Code:typedef struct _object Object; struct _object { unsigned long ID; char * name; int age; Object * prev; Object * next; };
Code://swapping two nodes(object1 and object2) void objectSwap(Object *object1, Object *object2){ Object *temp1=object1; /* store object1's original address to temp1 */ Object *temp2=object2; /* store object2's original address to temp2 */ //error checking if(object1 == NULL || object2 == NULL){ fprintf(stderr, "objectSwap() :: No node to swap.\n"); } else{ printf("temp1->prev : %d\t temp1->next : %d\n", temp1->prev, temp1->next); printf("temp2->prev : %d\t temp2->next : %d\n", temp2->prev, temp2->next); //******************************** in this part *************************************/ object1->next=temp2->next; /* set object1's next link to temp2(object2)'s next link */ object1->prev=temp2->prev; /* set object1's previous link to temp2(object2)'s previous link */ //************* I lost temp1's original address that I had stored at first****************/ printf("temp1->prev : %d\t temp1->next : %d\n", temp1->prev, temp1->next); printf("temp2->prev : %d\t temp2->next : %d\n", temp2->prev, temp2->next); if(temp2->prev != NULL) /* if temp2(object2)'s previous link is NULL that means temp2 is the first node(head) in the list. */ temp2->prev->next=object1; if(temp2->next != NULL) /* if temp2(object2)'s next link is NULL that means temp2 is the last node(tail) in the list. */ temp2->next->prev=object1; /* same process for object2 */ object2->next=temp1->next; object2->prev=temp1->prev; if(temp1->prev != NULL) temp1->prev->next=object2; if(temp1->next != NULL) temp1->next->prev=object2; } }



LinkBack URL
About LinkBacks




