以下代码是将二叉搜索树转换为双向链表的代码。它在 GDB 中运行良好,但在运行时崩溃。当我只有 2 个输入到二叉搜索树时,当有 2 个以上的输入时它会崩溃,它工作正常。代码可能有什么问题。双向链表不是循环链表。所以第一个节点的前一个是NULL,最后一个节点的下一个是NULL。
#include<stdio.h>
struct node{
int data;
struct node* large;
struct node* small;
};
typedef struct node* Node;
void add_to_tree(Node *root, int num){
Node current = *root;
Node temp_store;
Node new_node = malloc(sizeof(Node));
new_node->data = num;
new_node->large = NULL;
new_node->small = NULL;
if(current == NULL){
current = new_node;
*root = current;
}
else
{
while(current != NULL){
temp_store = current;
if(num > current->data)
current = current->large;
else
current = current->small;
}
if(num <= temp_store->data)
temp_store->small = new_node;
else
temp_store->large = new_node;
}
}
void display_list(Node head){
Node current = head;
if(head == NULL){
printf("\nThe list is empty");
}
else{
printf("\nThe list is:\n");
while(current !=NULL){
printf("%d\t", current->data);
current = current->large;
}
}
}
void join(Node a, Node b){
a->large = b;
b->small = a;
}
Node append(Node a, Node b){
Node aLast;
Node current;
if(a == NULL) return (b);
if(b == NULL) return (a);
current = a;
while(current->large != NULL)
current = current->large;
aLast = current;
join(aLast, b);
return (a);
}
Node bst_to_dll(Node root){
Node aList;
Node bList;
if(root == NULL)
return NULL;
aList = bst_to_dll(root->small);
bList = bst_to_dll(root->large);
root->small = NULL;
root->large = NULL;
aList = append(aList, root);
aList = append(aList, bList);
return aList;
}
int main(){
Node bin_tree = NULL;
Node d_list;
add_to_tree(&bin_tree, 1);
add_to_tree(&bin_tree, 2);
add_to_tree(&bin_tree, 3);
d_list = bst_to_dll(bin_tree);
display_list(d_list);
return 0;
}