双向链表两个结点互换位置(链表–数据结构)
双向链表两个结点互换位置
/*struct Node
{
int value;
Node *next;
Node *prev;
};*/
/*交换 buffer 和 i 两个结点(buffer在i右端)i---->buffer */
Node *before; //before 在i前面的结点
Node *after; //after 在buffer后面的结点
if (buffer->next == NULL)//若buffer是链表结尾
{
before = i->prev;
buffer->next = i;
buffer->prev = before;
i->next = NULL;
i->prev = buffer;
before->next = buffer;
}
else
{
before = i->prev;
after = buffer->next;
after->prev = i;
buffer->next = i;
buffer->prev = before;
i->next = after;
i->prev = buffer;
before->next = buffer;
}