首页 > 解决方案 > 在没有虚拟节点的链表前面插入

问题描述

我正在尝试插入按节点-> 名称排序的链表的前面,并且我在文件系统-> curr-> subdir 中没有虚拟节点


typedef struct Unix{

  struct Node *curr;
  struct Node *root;


}Unix;

typedef struct Node{

  struct Node *next;
  struct Node *subdir;
  struct Node *parent;
  char *name;
  char *field;

}Node;

下面是我插入按名称排序的链表


/* iter is a node used to traverse LL */

if(iter-> next == NULL && strcmp(iter->name, arg) > 0){
      if(iter == filesystem-> curr-> subdir){
/* error occurs when placing node in the front of the list */
    temp = malloc(sizeof(Node));

    temp-> parent = filesystem-> curr-> subdir-> parent;
    temp-> subdir = NULL;
    temp-> name = malloc(strlen(filesystem->curr->subdir->name) + 1);
    strcpy(temp-> name, filesystem-> curr-> subdir-> name);
    temp-> next = NULL;

/* add is the node that's being inserted */
    add-> next = temp;

    filesystem-> curr->subdir = add;

尝试将 add 作为 filesystem-> curr-> subdir 中的第一个节点并将前一个 subdir 节点移动到 add-> next 时发生错误。

编辑:该程序是unix机器的基本模拟。

标签: c

解决方案


这就是我开始怀疑错误的地方(就在代码的开头):

add-> parent = malloc(sizeof(Node));
add-> parent = filesystem-> curr;

你分配add-> parent了两次,这意味着它显然会获得后一个任务,而前一个任务“浪费了”。

除了程序中的内存泄漏(因为您将无法释放此分配的内存块)之外,设置add-> parent为该值很可能不是您的想法。


推荐阅读