【问题标题】:Creating a singly linked list with 2 structures in C在 C 中创建具有 2 个结构的单链表
【发布时间】:2013-09-25 19:33:12
【问题描述】:

我正在使用这两个结构,第一个保存员工信息,第二个保存列表信息:

typedef struct ListNodeTag{
  int idNumber;
  struct ListNodeTag *next;
} Employee;

typedef Employee Item;

typedef struct {
  int size;
  Item *head;
} List;

程序启动时,列表用这个函数初始化:列表在我的main中声明为List L;并像这样调用:Initialize (&L);

void Initialize (List *L) {
  L->size = 0;
  L->head = NULL;
}

从这里,我能够正确地将列表大小设置为 0。

然后我继续使用这两个函数将 Employee's 添加到列表中。第一个 (EmployeeCreation) 创建员工,而第二个 (Insert) 获取它并将其插入到列表中。该员工在我的主要声明为 Employee E;并像这样调用 EmployeeCreation(XXX, &E);

void EmployeeCreation (int idNumber, Employee *E) {   
  E->idNuber = idNumber;
  E->next = NULL;  
}

void Insert (Item X, int position, List *L) {
  int i;
  Item *currentPtr,*previousPtr;
  if(L->head == NULL)
  L->head = &X;
  else{
    currentPtr = L->head;
    for(i=0;i<position;i++){
      previousPtr = currentPtr;
      currentPtr = currentPtr->next;
    }
  previousPtr->next = &X;
  X.next = currentPtr; 
  L->size = L->size + 1;
  }  
}

当使用 4 个 ID 的测试文件运行时。第一个被正确读入并保存到列表中。第二个,替换第一个,列表长度加1(这部分我懂)。在此之后,程序段故障。这个错误会在我的程序中发生在哪里?即使 Insert 函数想要覆盖已经占用的位置,我认为它应该腾出空间并在新位置缝合。

【问题讨论】:

  • 这不会编译 - 因为数据结构 Employee 没有成员 name。那么为什么要给出实际编译的代码呢?
  • 我已经删除了,为简单起见,我删除了一些代码。
  • Insert函数中的Item是什么?
  • Item 已被定义为 Employee 结构体
  • @user2225940 - 很简单,但删除代码使其甚至无法编译,这并没有让我们有战斗的机会。

标签: c pointers data-structures struct linked-list


【解决方案1】:

您正在将局部变量 (item X) 的地址分配给 L-&gt;head

L-&gt;head = &amp;X;

当您从Insert 退出时,L-&gt;head 指向垃圾,因为X 不再可访问,要解决此问题,您可以:

void Insert (Item *X, int position, List *L) {
  ...
  L->head = X;
  ...  
}

Item *temp = malloc(sizeof(Item));

Insert(temp, ..., ...);
...
free(temp);

【讨论】:

  • 删除 & 会解决这个问题吗?完成此操作后,我收到一条错误消息,指出分配的类型不兼容。
  • 不,当您退出函数时,item 不再可访问。
  • 除了分配局部变量的地址,我还能如何将信息从员工创建移动到插入?
  • 您必须将X的地址传递给函数并删除&amp;
  • 没有其他方法了吗?使Item XItem *X 不适合这种情况。
【解决方案2】:

给你:

void Insert (Item X, int position, List *L) {
  int i;
  Item *currentPtr,*previousPtr;
  Item *newX = malloc(sizeof(Item);
  newX->idNunmber - X.idNumber;
  newX->next = NULL;

  if (L->head == NULL) {
      L->head = newX;
  } else {
    currentPtr = L->head;
    previousPtr = NULL;
    for(i=0;currentPtr!= NULL && i<position;i++) {
      previousPtr = currentPtr;
      currentPtr = currentPtr->next;
    }

    newX->next = currentPtr;
    previousPtr->next = newX; 
    L->size +=1;
  }  
}

【讨论】:

  • 感谢所有帮助,但是当我尝试将我的第二个员工添加到列表中时,我遇到了 seg 错误。
  • 我已经能够确定它在 for 循环开始时崩溃了,有什么想法吗?
  • L是如何初始化的?
  • 上面写了初始化函数,L初始化为List L;
  • 我相信你的代码很好,我的代码中有其他地方需要修复。
【解决方案3】:

在插入函数中,你可以简化这部分并检查--

else{
  currentPtr = L->head;
  for(i=0;i<position;i++){
    currentPtr = currentPtr->next;
  }
  Item *nextItm = currentPtr.next;
  currentPtr.next = &X;
  X .next = nextItm ; 
  L->size = L->size + 1;
}

【讨论】:

  • 用什么方式简化?我以为我已经达到了让它发挥作用的最低标准。
猜你喜欢
  • 1970-01-01
  • 2014-06-10
  • 2011-11-12
  • 1970-01-01
  • 1970-01-01
  • 2011-01-19
  • 2021-06-30
  • 2023-04-03
相关资源
最近更新 更多