【发布时间】:2018-08-30 04:08:18
【问题描述】:
我想填充一个位于二叉搜索树节点中的链表。 如果用户已经在列表中退出,则将 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;
}
【问题讨论】:
-
在您的
insertIP函数中,如果您点击else,您将需要遍历您的列表直到->ipNext=NULL,然后在该地址分配插入tmp,并将值设置为@987654330 @。由于您将始终分配if (search(username)==1),因此temp的分配应该在if (head->ipHead == NULL)之前。并且... 没有必要将malloc的返回值强制转换,没有必要。见:Do I cast the result of malloc?
标签: c dynamic data-structures linked-list binary-tree