【发布时间】:2016-12-22 20:30:35
【问题描述】:
我正在尝试创建一个稀疏(链接)结构,每个节点都指向它的所有子节点(总共 5 个)。 到目前为止,我只创建了第一个节点(称为“根”)。我正在尝试遍历链接结构,希望程序将返回“root”。 它给了我一个分段错误。
主类
Item n;
newDirectory();
printf("Folder root has been created.");
printf("Enter the name of the directory you want to traverse: ");
scanf("%s", n.name);
browseItem(n);
我创建的结构
typedef struct Directory{
//name of the file
char name[16];
//file content
char value[80];
_Bool isLeaf;
//if folder status = 1, if txt status = 2, if empty status = 0
int status;
struct Directory *firstchild;
struct Directory *secondchild;
struct Directory *thirdchild;
struct Directory *fourthchild;
struct Directory *fifthchild;
}Item;
我也包括了结构所在的类函数
//points to the first node: node "root"
Item *head;
//creates the first (head) node: "root"
void newDirectory(){
head = (Item *)malloc(sizeof(Item));
if(head == NULL){
printf("Unable to allocate memory.");
}else{
strcpy(head->name,"root");
head->status = 1;
head->firstchild = NULL;
head->secondchild = NULL;
head->thirdchild = NULL;
head->fourthchild= NULL;
head->fifthchild = NULL;
}
}
void browseItem(Item n) {
//how do I find the location of n
Item *tmp;
tmp = (Item *)malloc(sizeof(Item));
if(head == NULL){
printf("List is empty!");
}else{
tmp = **location of n**;
while(tmp!=NULL){
printf("%s", tmp->name);
tmp = tmp->firstchild;
tmp = tmp->secondchild;
tmp = tmp->thirdchild;
tmp = tmp->fourthchild;
tmp = tmp->fifthchild;
}
}
}
我的问题是如何首先搜索 n 的位置,以便 程序从该节点开始遍历。如果我有 更多来自根的节点,是否也会遍历子节点?
非常感谢!
【问题讨论】:
-
browseItem(..) 的期望行为是什么?我看不到返回值。此外,这不是一个链表,而是一棵树。此外,在这种连接结构中,通过递归更容易进行搜索。 browseItem 应该有两个参数。 1 要搜索的元素, 2. (temp) 根节点开始搜索。所以第一次调用browseItem(n, head);其他时候browseItem(n, head->children);
标签: c pointers linked-list