Could you please help me debug this code to swap two node of double link list? I am not able to figure out what i am doing wrong :(
here is the code:
Your logic will not work,
node2
is the first element in the doubly linked listnode1
and node2
are adjacent.Please fine the updated logic given below.
dll* swap_node(dll *head , dll *node1 , dll *node2) { dll* previous_to_node1 = NULL; dll* next_to_node1 = NULL; dll* previous_to_node2 = NULL; dll* next_to_node2 = NULL; if ((node1 == NULL) || (node2 == NULL)) return 0; previous_to_node1 = node1->previous; next_to_node1 = node1->next; previous_to_node2 = node2->previous; next_to_node2 = node2->next; if (previous_to_node1 != NULL) previous_to_node1->next = node2; if (next_to_node1 != NULL) next_to_node1->previous = node2; if (pevious_to_node2 != NULL) previous_to_node2->next = node1; if (next_to_node2 != NULL) next_to_node2->previous = node1; node1->next=next_to_node2; node1->previous=previous_to_node2; node2->next=next_to_node1; node2->previous=previous_to_node1; if (previous_to_node1 == NULL) { return node2; } else if(previous_to_node2 == NULL) { return node1; } return head; }