#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
答案 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`