debug help - swap 2 nodes of double link list

前端 未结 2 1966
醉梦人生
醉梦人生 2021-01-16 20:49

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:



        
2条回答
  •  隐瞒了意图╮
    2021-01-16 21:08

    Your logic will not work,

    1. If node2 is the first element in the doubly linked list
    2. If node1 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;
    }
    

提交回复
热议问题