如何在二叉搜索树的节点插入链表?

时间:2018-03-21 06:22:22

标签: c dynamic data-structures linked-list binary-tree

我想填充二进制搜索树节点中的链表。 如果用户已经退出列表,请将ip添加到该特定用户的链接列表中。

这是我到目前为止所尝试的:

我的数据结构:

typedef struct ip{
    int ip;
    struct ip *ipNext;
}IP;

typedef struct bstNode
{
    char data[32];
    struct bstNode* left;
    struct bstNode* right;
    IP *ipHead; //Pointer to linked list. 
}bstNode;

这是我遇到问题的地方

我的插入功能,用于将IP地址插入用户列表:

bstNode insertIP(bstNode *head, char *username, int ip){

 if (search(username)==1)
    {
        if (head->ipHead == NULL)
    {
        IP *temp; 
        temp = (IP*)malloc(sizeof(IP));
        temp->ip = ip;
        temp->ipNext = NULL;
    }else{
        head->ipHead->ip= ip;
        head->ipHead->ipNext=NULL;
    }
}

插入功能(可行):

bstNode *insert(bstNode *node, char *word)
{
    if(node==NULL){
        node= malloc(sizeof(bstNode));
        //IP* ipNode=malloc(sizeof(IP));
        strcpy(node->data, word);
        node->left=NULL;
        node->right=NULL;
    }
    else{
        if(strcmp(word, node->data)<0)
            node->left=insert(node->left, word);
        else if(strcmp(word, node->data)>0)
            node->right=insert(node->right, word);
    }
    return node;
}

搜索功能(可行):

void search(char* user, bstNode* root)  
{
    int res;
    if( root!= NULL ) {
        res = strcmp(root, root->data);
        if( res < 0)
            search( user, root->left);
        else if( res > 0)
            search( user, root->right);
        else
            printf("User Found\n");   
            return 1;                       
    }
    else printf("\nNot in tree\n");
    return 0;
}

3 个答案:

答案 0 :(得分:0)

当您发现树中已存在该用户时,首先您必须存储包含给定用户的bstNode。之后,您必须遍历bstNode的链接列表,以便在最后添加ip。如果链接链接为NULL,则代码还有一个问题。您必须将新节点地址分配给ipHead。目前,您已经创建了一个临时节点,而不是将其分配给头部。

答案 1 :(得分:0)

第1期:当您创建temp时,您不会将其分配给head->ipHead

第2期:当ipHead存在时,您仍然需要为新列表节点分配内存,如果要在最后添加它,则必须遍历整个列表。您也可以在列表的开头添加它。

第3期:如果找到用户名,搜索功能应返回树中的节点。我想你不想总是在第一个树节点上添加新的列表节点。我建议你在函数中使用局部变量遍历树 - 而不是递归。

答案 2 :(得分:0)

最近,我对二进制搜索树进行了编码,其中每个树节点托管一个链接列表(列表节点被单链接),并且我使用了以下数据结构(如果有人需要整个代码,请告诉我)。

// data in each
// list node
struct data_info
{
    //body of data
};

typedef struct data_info Item;

// list node
typedef struct lnode
{
    Item data_item;
    struct lnode * next;
} Lnode;

// List points to
// first list node
typedef Lnode * List;

// tree node contains
// linked list
typedef struct trnode
{
    List list_item;
    struct trnode * left;   // pointer to right branch
    struct trnode * right;  // pointer to left branch
} Trnode;

// tree of linked lists
typedef struct tree
{
    Trnode * root;          // pointer to root of tree
    int size;               // number of list nodes in tree
} Tree;