本文介绍了调试的帮助 - 交换双链表的2个节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

能否请你帮我调试这个code换双链表的双节点?我无法找出什么我做错了:(

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 :(

这里是code:

dll* swap_node(dll *head , dll *node1 , dll *node2) {
   dll *tmp;
   int flag=0;

   if(node1->prev!=NULL) {
       node1->prev->next=node2;
   } else {
       flag=1;
   }
   if(node1->next!=NULL) {
       node1->next->prev=node2;
   }

   if(node2->prev!=NULL) {
       node2->prev->next=node1;
   }
   if(node2->next!=NULL) {
       node2->next->prev=node1;
   }

   tmp=node1->next;
   node1->next=node2->next;
   node2->next=tmp;

   tmp=node1->prev;
   node1->prev=node2->prev;
   node2->prev=tmp;

   if(flag==1) {
       head=node2;
   }
   return head;
}

在此先感谢

推荐答案

您的逻辑是行不通的,


  1. 如果节点2 是双向链表的第一个元素

  2. 如果节点1 节点2 是相邻的。

  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;
}

这篇关于调试的帮助 - 交换双链表的2个节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-31 06:18