将树转换为循环双向链表

时间:2014-05-20 15:40:25

标签: c pointers

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

 /* The node type from which both the tree and list are built */
struct node
{
    int data;
    struct node *small;
    struct node *large;
};
typedef struct node *Node;

static void join(Node a, Node b)
{
    a->large = b;
    b->small = a;
}

static Node append(Node a, Node b)
{
    Node aLast, bLast;

    if (a == NULL)
        return (b);
    if (b == NULL)
        return (a);

    aLast = a->small;
    bLast = b->small;

    join(aLast, b);
    join(bLast, a);

    return (a);
}

在这个实现中,如果不是在append函数中定义局部变量,即aLast和bLast,而是直接连接(a-&gt; small,b)和join(b-&gt; small,a)被调用,输出会截断到列表中只有一个元素。 这是问题的链接:bst to circular

1 个答案:

答案 0 :(得分:1)

您的join函数会更改结构中small元素的值。因此:

aLast = a->small;
bLast = b->small;  // This saves the current value of `b->small`
                   // before `join(aLast, b)` changes it

join(aLast, b);    // This call to join changes the value of `b->small`
join(bLast, a);    // bLast still has the *old* value of `b->small`

与此不一样:

join(a->small, b); // This call to join changes the value of `b->small`
join(b->small, a); // This call uses the *new* value of `b->small`