在双链表中交换两个节点

时间:2012-10-08 23:39:07

标签: c doubly-linked-list

我必须编写一个程序,它基本上对链表中的节点进行排序。我有5个函数需要为这个任务编写,我被困在其中一个。我遇到问题的功能是交换两个节点。该函数的标题如下:

void swap (struct lnode** head, struct lnode* n1, struct lnode* n2)

只要两个节点不相邻,我就能正常工作。我们提供了一个list.h文件,我们应该使用两个函数evictNode(struct lnode** head, struct lnode* node)void insertNode (struct lnode** head, struct lnode* prevNode, struct lnode* nodeToBeInserted)。这些函数也处理nextprevious指针的重新分配。我不完全确定如果它们彼此相邻,如何交换节点。我试过把它画出来,但一直无法绕过它。

哦顺便说一句,我处理其余节点的方式是使用以下代码:

evictNode(head, n1);
evictNode(head, n2);
insertNode(head, n1prev, n2);
insertNode(head, n2prev, n1);

编辑:尝试

struct lnode* temp = n2;
insertNode(head,n1prev,temp)
evictNode(head, n2)

其中struct lnode* n1prev = nodeGetPrev(n1) 有两个函数可以返回上一个/下一个指针

1 个答案:

答案 0 :(得分:1)

我会按照以下方式进行:

struct lnode* tmp = nodeGetPrev(n1);
/*
 * Remove n1 and insert it before n2
 * note to calling nodeGetPrev(n2) after removing n1
 */
evictNode( head, n1 );
insertNode( head, nodeGetPrev(n2), n1 );
/* If n2 were before n1 and we insert n1 before n2, swap is done */
if( tmp != n2 ) {
    evictNode( head, n2 );
    insertNode( head, tmp, n2 );
}