2012-02-26 24 views
0

假设我有一个外部库BST,处理自定义数据类型插入一个BST含自定义数据

这里有new_node,插入和搜索函数C二叉搜索树.C,假设我读txt文件的车型:

#include <stdio.h> 
#include <stdlib.h> 
#include "bst.h" 
#include <string.h> 

#define MAX 50 

typedef struct data_t{ 
    int gg,mm,aaaa;  
}data; 

typedef struct accesories_t{ 
    char name[MAX]; 
    int price; 
    struct accesories_t *next;  
}accesories; 

typedef struct model_t{ 
    //int index; 
    char name[MAX]; 
    char file_a[MAX]; 
    data date; 
    int price; 
    accesories *acs; 
}model; 


int main(int argc, char *argv[]) 
{ 
    int menu=0; 

    char nf[MAX]; 

    char name[MAX]; 
    char fa[MAX]; 
    int price,gg,mm,a; 

    strcpy(nf,argv[1]); 

    FILE *fp=fopen(nf,"+r"); 
    model m; 
    struct bst_node* root = NULL; 

    while(fscanf(fp,"%s %d//%d//%d %d %s",name,gg,mm,a,price,fa)!=EOF){ 
     strcpy(m.name,name); 
     strcpy(m.file_a,fa); 
     m.date.gg=gg; 
     m.date.mm=mm; 
     m.date.aaaa=a; 
     m.price=price; 
     m.index=index++; 

     insert(&root ,m); 
    } 

    system("PAUSE"); 
    return 0; 
} 

所以我的问题出现在搜索功能,如何管理自定义数据的比较(假设插入模型由南排序e(strcmp)? 我我如何能名字传给鉴于bst.c不知道我的模型结构是如何做出的bst.c很困惑。

我应该修改BST库,也许在BST结构添加数据之前,某种指标和使用,作为比较?

OK我已经成功通过添加字符串键的结构BST

我想要现在实现是返回void *的数据型铸造成模型结构, 假设内部修复_I得到了与包含数据的节点树,有一次我做搜索,我想返回 例如包含在其上的一个节点和工作数据,任何线索????

试图像成才没有任何成功 假设节点从一个搜索功能

model *m; 
m=(model*)node->data; 

返回的节点我怎么能做到这一点?

+0

你可以在一个额外的参数传递给它的函数指针需要比较的所有功能。 – wildplasser 2012-02-26 15:10:05

+0

或者你可以通过在BST创建时间 – Kevin 2012-02-26 15:13:29

+0

完全函数指针。 (但是这将创建一个特殊的“头”节点类型的需要)你走了。在你的服务.... – wildplasser 2012-02-26 15:14:52

回答

0

实施例用于使用比较功能作为回调。为简洁起见省略了定义。

int llist_cmp(struct llist *l, struct llist *r) 
{ 
if (!l) return 1; 
if (!r) return -1; 
return strcmp(l->payload,r->payload); 
} 

struct llist * llist_split(struct llist **hnd, int (*cmp)(struct llist *l, struct llist *r)) 
{ 
struct llist *this, *save, **tail; 

for (save=NULL, tail = &save; this = *hnd;) { 
     if (! this->next) break; 
     if (cmp(this, this->next) <= 0) { hnd = &this->next; continue; } 
     *tail = this->next; 
     this->next = this->next->next; 
     tail = &(*tail)->next; 
     *tail = NULL; 
     } 
return save; 
} 

struct llist * llist_merge(struct llist *one, struct llist *two, int (*cmp)(struct llist *l, struct llist *r)) 
{ 
struct llist *result, **tail; 

for (result=NULL, tail = &result; one && two; tail = &(*tail)->next) { 
     if (cmp(one,two) <=0) { *tail = one; one=one->next; } 
     else { *tail = two; two=two->next; } 
     } 
*tail = one ? one: two; 
return result; 
} 

顺便说一句:将上面的片段手柄链表,但用于使函数指针的机制是一样的树木,当然。毕竟这是功课;-)

+0

我仍然无法找到如何在我的bst.c函数中管理model.name的方法,它告诉我应该使用void指针,但是例如当我将模型项传递给它时调用new_node函数我没有Ideea如何比较该item.name – 2012-02-26 17:02:08

+0

那么,在你的main()中你声明m是一个(结构)模型。将它改为一个指针,并且在你需要的时候将malloc的空间用于m(在fscanf()循环中)插入函数也可能需要改变(它已经将void *指针作为参数)。并创建比较函数,可能会比较结构中的名称,类似于我的代码片段。 – wildplasser 2012-02-26 17:49:59