【问题标题】:Browsing through a linked List浏览链接列表
【发布时间】: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


【解决方案1】:

Segfault 通常是由于数据传输不正确造成的。您的代码和逻辑存在一些问题。让我尽量回答你所有的问题:

首先,您的链表并不是真正的链表,它是一棵树。链表将指向下一个节点。这是一个单链表,一个双向链表会指向下一个节点,前一个节点。它们都是一样的,除了一棵树有更多的孩子,而链表只有一个孩子,双向链表也有一个指向父元素(或前一个元素)的指针。

您的第二个问题似乎是,我如何获得 root 权限?

“我正在尝试遍历链接结构,希望程序返回'root'。”

目前,您的代码是这样的:root--> child 1, child 2, child 3(这是一棵树)。如果您希望您的代码改为链表,则它必须是 root--> child1 --> child2 --> child3 ... 等等。但是,您的链表是单链表,这意味着您只能前进,而不能后退。如果你想回到根,它会是null<--root--> <--child1--> <--child 2 --> <-- ... -->,等等(你必须有一个指针,指向前一个节点,就像一个双向链表)。

那么对于你如何找到 n 的问题?

//如何找到n的位置

只有从 root 开始,然后以这种方式遍历链表,才能做到这一点。使用链表最简单的方法是:

Item tmp = head->child1;
while (tmp != null)
{
    if (tmp -> name == n)
    {
         print "Found n!" + tmp->name
         break;
    }
    tmp = tmp -> nextChild;

}

此代码只是一个伪代码,以使其看起来更简单。

如果它是一棵树,那么用户将不得不使用广度优先算法或深度优先算法来找到 n。如果您的代码试图模仿文件结构,则应使用树,而不是链表。

【讨论】:

    猜你喜欢
    • 2012-09-27
    • 2012-06-05
    • 1970-01-01
    • 2014-03-23
    • 2019-03-18
    • 2023-02-10
    • 2013-10-25
    • 2012-02-21
    • 1970-01-01
    相关资源
    最近更新 更多