【问题标题】:Swapping nodes in double linked list交换双链表中的节点
【发布时间】:2013-11-20 12:06:03
【问题描述】:

我正在尝试实现一个交换我的双链表的两个节点的函数,以便对当前目录的内容进行排序。但是我的函数似乎“删除”了我列表中的一些元素,这里是代码:

void node_swap(struct s_node *left, struct s_node *right)
{
  struct s_node *tmp;

  tmp = left->prev;
  if (tmp)
   {
      tmp->next = right;
      right->prev = tmp;
   }
  else
      right->prev = NULL;

  left->prev = right;
  left->next = right->next;
  right->next = left;
  right->next->prev = left->prev;
}

我看不出这有什么问题?

【问题讨论】:

  • 为什么不直接交换数据?
  • 为什么不能直接交换两个节点的数据内容?
  • 我可以,但是这样不是更慢吗?
  • 取决于数据。您的数据类型是什么?
  • @user3012923 那么仅仅交换一个char *显然比交换4个struct s_node *s要快。

标签: c linked-list


【解决方案1】:

如果你写下你想做的事情,你可以实现一个非常简单直接的解决方案。

[[工作代码在答案末尾]]

例如,如果你有两个节点要交换(比如A和B),根据节点的位置有两种可能性。它们可以相邻也可以不相邻。

相邻的情况

在相邻的情况下,你可以写:

[X] - [A] - [B] - [Y]

A->prev = X;
A->next = B;
B->prev = A;
B->next = Y;

如果你把 A 换成 B,你会得到这样的结果:

[X] - [B] - [A] - [Y]

A->prev = B;
A->next = Y;
B->prev = X;
B->next = A;

这就是你想要的。您必须重新排列指针以交换两个节点 A 和 B。

如果你使用矩阵形式,规则会更直观:

     A B               A B 
prev X A    =>    prev B X
next B Y          next Y A

或者只写矩阵:

X A   --\   B X
B Y   --/   Y A

注意,交换矩阵顺时针旋转 90 度。如果你索引矩阵中的元素,你可以组成一个关联表:

0 1  --\  2 0
2 3  --/  3 1

因此,如果将指针存储在数组中,则可以轻松地重新排列它们:

0,1,2,3 -> 2,0,3,1

不相邻的情况

您也可以为不相邻的情况制定类似的规则:

[W] - [A] - [X] - ... - [Y] - [B] - [Z]

A->prev = W;
A->next = X;
B->prev = Y;
B->next = Z;

用 B 交换 A:

[W] - [B] - [X] - ... - [Y] - [A] - [Z]

A->prev = Y;
A->next = Z;
B->prev = W;
B->next = X;

     A B               A B 
prev W Y    =>    prev Y W
next X Z          next Z X

W Y   --\   Y W
X Z   --/   Z X

0 1  --\  1 0
2 3  --/  3 2

0,1,2,3 -> 1,0,3,2

指向节点的指针

因为我们处理的是链表,仅仅改变特定节点中的指针是不够的。我们必须更新指向我们想要交换的节点的指针。该指针位于可交换对象的附近。

请注意,位于我们的指针指向的节点中的指针始终指向我们自己。

A->prev->next = A
A->next->prev = A

所以根据关联规则更新指针后,只需将外部指针指向给定节点,就完成了!只要确保邻居当然存在即可。

您还需要检查节点A是否在节点B之前链接。如果没有,则需要交换两个参数。感谢kralyk 的提醒。

这些信息足以编写进行交换的必要函数。

交换函数及其辅助函数

int areTheyNeighbours(Node A,Node B) {
    return ( A->next == B && B->prev == A ) || ( A->prev == B && B->next == A );
}

void refreshOuterPointers(Node A) {
    if (A->prev != NULL)
        A->prev->next = A;

    if (A->next != NULL)
        A->next->prev = A;
}

void swap(Node A,Node B) {
    Node swapperVector[4];
    Node temp;

    if (A == B) return;

    if (B->next == A) {
        temp = A;
        A = B;
        B = temp;
    }

    swapperVector[0] = A->prev;
    swapperVector[1] = B->prev;
    swapperVector[2] = A->next;
    swapperVector[3] = B->next;

    if (areTheyNeighbours(A,B)) {
        A->prev = swapperVector[2];
        B->prev = swapperVector[0];
        A->next = swapperVector[3];
        B->next = swapperVector[1];
    } else {
        A->prev = swapperVector[1];
        B->prev = swapperVector[0];
        A->next = swapperVector[3];
        B->next = swapperVector[2];
    }

    refreshOuterPointers(A);
    refreshOuterPointers(B);
}

演示工作程序

以下程序的optput:

Initial state:   [1]-[2]-[3]-[4]
--------------------------------
[1] <-> [2]:     [2]-[1]-[3]-[4]
[1] <-> [2]:     [1]-[2]-[3]-[4]
[2] <-> [1]:     [2]-[1]-[3]-[4]
[2] <-> [1]:     [1]-[2]-[3]-[4]
--------------------------------
[1] <-> [3]:     [3]-[2]-[1]-[4]
[1] <-> [3]:     [1]-[2]-[3]-[4]
[3] <-> [1]:     [3]-[2]-[1]-[4]
[3] <-> [1]:     [1]-[2]-[3]-[4]
--------------------------------
[1] <-> [4]:     [4]-[2]-[3]-[1]
[1] <-> [4]:     [1]-[2]-[3]-[4]
[4] <-> [1]:     [4]-[2]-[3]-[1]
[4] <-> [1]:     [1]-[2]-[3]-[4]
--------------------------------
[2] <-> [3]:     [1]-[3]-[2]-[4]
[2] <-> [3]:     [1]-[2]-[3]-[4]
[3] <-> [2]:     [1]-[3]-[2]-[4]
[3] <-> [2]:     [1]-[2]-[3]-[4]
--------------------------------
[2] <-> [4]:     [1]-[4]-[3]-[2]
[2] <-> [4]:     [1]-[2]-[3]-[4]
[4] <-> [2]:     [1]-[4]-[3]-[2]
[4] <-> [2]:     [1]-[2]-[3]-[4]
--------------------------------
[3] <-> [4]:     [1]-[2]-[4]-[3]
[3] <-> [4]:     [1]-[2]-[3]-[4]
[4] <-> [3]:     [1]-[2]-[4]-[3]
[4] <-> [3]:     [1]-[2]-[3]-[4]

您可以通过以下链接立即运行代码: http://codepad.org/UHcmmag1

更新了链接,修正了交换功能:http://codepad.org/LbRYjvPr

#include <stdio.h>
#include <stdlib.h>

typedef struct node_v {
    int id;
    struct node_v* prev;
    struct node_v* next;
} Node_v;

typedef Node_v* Node;

void print(Node node) {
    while (node->prev != NULL)
        node = node->prev;

    printf("   [%d]",node->id);

    while (node->next != NULL) {
        node = node->next;
        printf("-[%d]",node->id);
    }

    printf("\n");
}

void connect(Node first,Node second) {
    first->next = second;
    second->prev = first;
}

Node createNode(int id) {
    Node node = (Node)malloc(sizeof(Node_v));
    node->id = id;
    node->prev = NULL;
    node->next = NULL;
    return node;
}

int areTheyNeighbours(Node A,Node B) {
    return ( A->next == B && B->prev == A ) || ( A->prev == B && B->next == A );
}

void refreshOuterPointers(Node A) {
    if (A->prev != NULL)
        A->prev->next = A;

    if (A->next != NULL)
        A->next->prev = A;
}

void swap(Node A,Node B) {
    Node swapperVector[4];
    Node temp;

    if (A == B) return;

    if (B->next == A) {
        temp = A;
        A = B;
        B = temp;
    }

    swapperVector[0] = A->prev;
    swapperVector[1] = B->prev;
    swapperVector[2] = A->next;
    swapperVector[3] = B->next;

    if (areTheyNeighbours(A,B)) {
        A->prev = swapperVector[2];
        B->prev = swapperVector[0];
        A->next = swapperVector[3];
        B->next = swapperVector[1];
    } else {
        A->prev = swapperVector[1];
        B->prev = swapperVector[0];
        A->next = swapperVector[3];
        B->next = swapperVector[2];
    }

    refreshOuterPointers(A);
    refreshOuterPointers(B);
}

int main() {
    Node n1 = createNode(1);
    Node n2 = createNode(2);
    Node n3 = createNode(3);
    Node n4 = createNode(4);

    connect(n1,n2);
    connect(n2,n3);
    connect(n3,n4);

    printf("\nInitial state:");
    print(n2);

    printf("--------------------------------\n");

    printf("[1] <-> [2]:  ");
    swap(n1, n2);
    print(n1);

    printf("[1] <-> [2]:  ");
    swap(n1, n2);
    print(n1);

    printf("[2] <-> [1]:  ");
    swap(n2, n1);
    print(n1);

    printf("[2] <-> [1]:  ");
    swap(n2, n1);
    print(n1);

    printf("--------------------------------\n");

    printf("[1] <-> [3]:  ");
    swap(n1, n3);
    print(n2);

    printf("[1] <-> [3]:  ");
    swap(n1, n3);
    print(n2);

    printf("[3] <-> [1]:  ");
    swap(n3, n1);
    print(n2);

    printf("[3] <-> [1]:  ");
    swap(n3, n1);
    print(n2);

    printf("--------------------------------\n");

    printf("[1] <-> [4]:  ");
    swap(n1, n4);
    print(n3);

    printf("[1] <-> [4]:  ");
    swap(n1, n4);
    print(n3);

    printf("[4] <-> [1]:  ");
    swap(n4, n1);
    print(n3);

    printf("[4] <-> [1]:  ");
    swap(n4, n1);
    print(n3);

    printf("--------------------------------\n");

    printf("[2] <-> [3]:  ");
    swap(n2, n3);
    print(n3);

    printf("[2] <-> [3]:  ");
    swap(n2, n3);
    print(n3);

    printf("[3] <-> [2]:  ");
    swap(n3, n2);
    print(n3);

    printf("[3] <-> [2]:  ");
    swap(n3, n2);
    print(n3);

    printf("--------------------------------\n");

    printf("[2] <-> [4]:  ");
    swap(n2, n4);
    print(n3);

    printf("[2] <-> [4]:  ");
    swap(n2, n4);
    print(n3);

    printf("[4] <-> [2]:  ");
    swap(n4, n2);
    print(n3);

    printf("[4] <-> [2]:  ");
    swap(n4, n2);
    print(n3);

    printf("--------------------------------\n");

    printf("[3] <-> [4]:  ");
    swap(n3, n4);
    print(n4);

    printf("[3] <-> [4]:  ");
    swap(n3, n4);
    print(n4);

    printf("[4] <-> [3]:  ");
    swap(n4, n3);
    print(n4);

    printf("[4] <-> [3]:  ");
    swap(n4, n3);
    print(n4);

    printf("--------------------------------\n");

    return 0;
}

【讨论】:

  • 如果 A 和 B 是邻居,则此方法不起作用,但 B 在 A 之前(即,如果您尝试交换 [2] &lt;-&gt; [1])。在这种情况下,您要么需要将矩阵旋转 -90°,要么检测 B 在 A 之前并首先交换 A 和 B 指针。老实说,我认为矩阵使代码过于复杂。我只是使用一个交换函数/宏。
  • 绝对有效的评论。在交换方法解决问题之前进行一些检查。代码将被更新。
  • 嗯,矩阵变换只是相对简单的交换函数背后的想法。你也可以通过指针的杂耍来想出交换方法,但我认为矩阵的方法更清晰一些。
【解决方案2】:

假设这是您的初始结构TMP -&gt; L -&gt; R -&gt; X 您没有正确更新 X->prev。在你的最后一行right-&gt;next-&gt;prev = left-&gt;prev; right->next 是左边。所以你正在更新left的prev,这是错误的。相反,你应该这样做

if(left->next != null)
   left->next(which is X)->prev = left

所以,我认为这会奏效

void node_swap(struct s_node *left, struct s_node *right)
{
  struct s_node *tmp;

  tmp = left->prev;
  if (tmp)
      tmp->next = right;
  right->prev = tmp;

  left->prev = right;
  left->next = right->next;
  right->next = left;
  if(left->next != null)
     left->next(which is X)->prev = left
}

【讨论】:

  • 试过这个,结果好像是一样的,排序完成后我还是丢了3个元素。
  • 顺便说一句,您应该在执行此操作之前进行空检查。也就是说,如果初始 R->next 为 null,您不应该这样做
  • 仍然是相同的输出...发现正确打印的两个元素是第一个和最后一个,它们之间的每个元素都已“丢失”。
【解决方案3】:

根据您问题中发布的代码,我推断您的函数假设您正在交换相邻节点。

尝试以下方法:

if ( left->prev )
    left->prev->next = right;

if ( right->next )
    right->next->prev = left;

left->next  = right->next;
right->prev = left->prev;

right->next = left;
left->prev = right;

编辑:根据您在原始问题中的评论,执行以下操作要快得多:

char* tmpName = right->name;
right->name = left->name;
left->name = tmpName;

【讨论】:

  • 您的解决方案仅适用于相邻节点(例如x - A - B -y 但不适用于x - A - y - B - z)
  • @ensc 是的,我认为在检查问题中的代码后假定相邻节点。我将编辑帖子以指定这一点。
  • 谢谢,它可以工作,虽然 Valgrind 似乎对此有点不高兴,两个'条件跳转或移动取决于未初始化的值'
  • @user3012923 您应该在函数的第一行验证 left 和 right 不是 NULL。如果任何一个(或两者)是NULL,则显示错误并返回。
  • 在函数的开头做了一个 if (!left || !right) {return ;},但是 Valgrind 仍然输出这些错误。
【解决方案4】:

非常短的代码,运行效率很高,花了 2 个小时完成:

你需要交换两个节点...

还要确保在两个方向上保留两个交换节点与第三个和最后一个节点之间存在的链接。

static inline void  swap_list(t_lst **lst)
{
    t_lst   *tmp;

    if ((*lst)->next)   // you need to make sure you have at least 2 items in your list
    {
        tmp = *lst;                 // let's store 1st node's address, that will become the second one after the swap
        *lst = (*lst)->next;        // Reversely our 2nd one will become the 1st one after the swap. It also allows us to set the beginning of our list.
/*
** Now you need to work on the 6 links that exist : between the last elem (that may be the 2nd one)
** and the 1st one you have 2 links (next and prev), same between the 1st one
** and the 2nd one (2 links again) and finally 2 links between the 2nd one
** and the 3d one (that may be the first node)
*/
        tmp->next = (*lst)->next;   // tmp will have second position and needs to point to the third elem. Since *lst is now (*lst)->next, here we refer to the 3rd elem.
        tmp->next->prev = tmp;      // we have then to tell this third elem where stands the second one with this line.
        (*lst)->prev = tmp->prev;   // before destroying the link to last node that tmp contains, we assign it to the future 1st elem of our list
        tmp->prev = *lst;           // now we can safely tell the second node its link to the first.
        (*lst)->next = tmp;         // and reversely tells where is the second elem after the first.
        (*lst)->prev->next = *lst;  // finally we tell the last node where it the first one.
    }
}

希望对你有帮助。

ps:如果你想知道:

typedef struct      s_lst
{
    void            *data; // or a more specific type if you wish
    struct s_lst    *prev;
    struct s_lst    *next;
}                   t_lst;

【讨论】:

    猜你喜欢
    • 2015-03-11
    • 1970-01-01
    • 1970-01-01
    • 2017-08-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-07
    相关资源
    最近更新 更多